在创业板开启的ActiveRecord的扩展 [英] Turning extension of ActiveRecord in gem
问题描述
此扩展名来创建 cache_find
方法的应用程序的所有型号(我创建这个使用的这个帖子)。
This extension create cache_find
method for all models of app (I've create this using this post).
配置/ active_record_extension.rb
config/active_record_extension.rb
module ActiveRecordExtension
extend ActiveSupport::Concern
# add your instance methods here
def flush_find
Rails.cache.delete([self.class.name, :cached_find, id])
end
included do
after_commit :flush_find
end
module ClassMethods
def cached_find id
Rails.cache.fetch([self.name, :cached_find, id]) { self.find(id) }
end
end
end
# include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension)
我把这个code成宝石,并加入到这一回购。
所以我要动态地添加这个方法是这样的:
So I want to add this methods dynamically, something like this:
class User << ActiveRecord::Base
# id, name, email, age...
cached :find, :find_by_name, :find_by_email
end
和上面的code应该产生 cached_find
, flush_find
, cached_find_by_name
, flush_find_by_name
...你得到它。
and the above code should generate cached_find
, flush_find
, cached_find_by_name
, flush_find_by_name
... You get it.
我需要帮助:
- 测试
Rails.cache
方法model_caching
宝石。 - 创建code动态添加方法的基础上
缓存
方法的参数应用模式。
- Test
Rails.cache
methods inmodel_caching
gem. - Create code to dynamically add methods to app models based on
cached
method arguments.
这帮助了我,但不符合所有的一些链接:
Some links that helped me but do not meet all:
https://github.com/radar/guides/ BLOB /主/ extending-active-record.md
http://railscasts.com/episodes/245-new-gem-与打捆
http://guides.rubyonrails.org/plugins.html
下跌免费克隆和完善宝石code 。
Fell free to clone and improve gem code.
推荐答案
您不必砍的ActiveRecord :: Base的。您可以添加什么马克 - 亚历山大说,右转进入你的关心,像这样:
You don't have to hack ActiveRecord::Base. You can add what Marc-Alexandre said right into your concern, like so:
module ActiveRecordExtension
extend ActiveSupport::Concern
...
module ClassMethods
def cached(*args)
define_method "cached_#{arg.to_s}" do
# do whatever you want to do inside cached_xx
end
define_method "flush_#{arg.to_s}" do
# do whatever you want to to inside flush_xx
end
end
end
end
另外,我也不会自动包括扩展名直接在ActiveRecord的,我认为这是最好明确其包含在你要使用它的车型。
Also, I would not auto include the extension directly in ActiveRecord, I think it's better to explicitly include it in the models you are going to use it.
这篇关于在创业板开启的ActiveRecord的扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!