简体   繁体   English

在Rails 3中如何/何时/何处扩展Gem类(通过class_eval和Modules)?

[英]How/When/Where to Extend Gem Classes (via class_eval and Modules) in Rails 3?

What is the recommended way to extend class behavior, via class_eval and modules (not by inheritance) if I want to extend a class buried in a Gem from a Rails 3 app? 如果我想从Rails 3应用程序扩展埋在Gem中的类,那么通过class_eval和模块(而不是通过继承)扩展类行为的推荐方法是什么?

An example is this: 一个例子是:

I want to add the ability to create permalinks for tags and categories (through the ActsAsTaggableOn and ActsAsCategory gems). 我想添加为标签和类别创建永久链接的功能(通过ActsAsTaggableOn和ActsAsCategory宝石)。

They have defined Tag and Category models. 他们定义了TagCategory模型。

I want to basically do this: 我想基本上这样做:

Category.class_eval do
  has_friendly_id :title
end

Tag.class_eval do
  has_friendly_id :title
end

Even if there are other ways of adding this functionality that might be specific to the gem, what is the recommended way to add behavior to classes in a Rails 3 application like this? 即使有其他方法可以添加可能特定于gem的此功能,在这样的Rails 3应用程序中向类添加行为的推荐方法是什么?

I have a few other gems I've created that I want to do this to, such as a Configuration model and an Asset model. 我有一些我想创建的其他宝石,比如Configuration模型和Asset模型。 I would like to be able to add create an app/models/configuration.rb model class to my app, and it would act as if I just did class_eval . 我希望能够在我的app/models/configuration.rb添加一个app/models/configuration.rb模型类,它就好像我只是做了class_eval

Anyways, how is this supposed to work? 无论如何,这应该是怎么回事? I can't find anything that covers this from any of the current Rails 3 blogs/docs/gists. 我找不到任何有关当前Rails 3博客/文档/要点的内容。

I do this as follows, first add a file to config/initializers where you can require the files that contain your extensions: 我按如下方式执行此操作,首先将文件添加到config / initializers,您可以在其中要求包含扩展名的文件:

# config/initializers/extensions.rb
require "#{Rails.root}/app/models/category.rb"
require "#{Rails.root}/app/models/tag.rb"

Then you can just re-open the classes and add whatever else you need: 然后你可以重新打开这些类并添加你需要的任何东西:

# app/models/category.rb
class Category
  has_friendly_id :title
end

Only downside is that the server has to be restarted for any changes to these files to take effect, not sure if there is a better way that would overcome that. 唯一的缺点是必须重新启动服务器才能使这些文件的任何更改生效,不确定是否有更好的方法可以解决这个问题。

You can use rails_engine_decorator gem: https://github.com/atd/rails_engine_decorators 您可以使用rails_engine_decorator gem: https//github.com/atd/rails_engine_decorators

Just add in your Gemfile: 只需添加您的Gemfile:

gem 'rails_engine_decorator'

And user class_eval in your decorators: 并且装饰者中的用户class_eval

/app/decorators/models/category_decorator.rb
/app/decorators/models/tag_decorator.rb

It works for me. 这个对我有用。 I hope you find it useful! 希望对你有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM