Rails扩展ActiveRecord :: Base
我已经做了一些关于如何扩展ActiveRecord:Base类的阅读,这样我的模型就会有一些特殊的方法。 什么是简单的方法来扩展它(一步一步的教程)?
有几种方法:
使用ActiveSupport :: Concern(首选)
阅读ActiveSupport :: Concern文档以获取更多详细信息。
在lib
目录中创建一个名为active_record_extension.rb
的文件。
module ActiveRecordExtension
extend ActiveSupport::Concern
# add your instance methods here
def foo
"foo"
end
# add your static(class) methods here
class_methods do
#E.g: Order.top_ten
def top_ten
limit(10)
end
end
end
# include the extension
ActiveRecord::Base.send(:include, ActiveRecordExtension)
在config/initializers
目录下创建一个名为extensions.rb
的文件,并将以下行添加到文件中:
require "active_record_extension"
继承(首选)
参考Toby的答案。
猴子修补(应该避免)
在config/initializers
目录下创建一个名为active_record_monkey_patch.rb
。
class ActiveRecord::Base
#instance method, E.g: Order.new.foo
def foo
"foo"
end
#class method, E.g: Order.top_ten
def self.top_ten
limit(10)
end
end
有关Jamie Zawinski的正则表达式的着名引用可以重新用于说明与猴子修补有关的问题。
有些人遇到问题时,会想“我知道,我会用猴子补丁”。现在他们有两个问题。
猴子修补很简单,快捷。 但是,节省的时间和精力总是在未来的某个时候提取出来。 与复利。 现在我限制猴子修补,以便在轨道控制台中快速构建原型解决方案。
你可以扩展这个类并简单地使用继承。
class AbstractModel < ActiveRecord::Base
self.abstract_class = true
end
class Foo < AbstractModel
end
class Bar < AbstractModel
end
你也可以使用ActiveSupport::Concern
并使用更多的Rails核心ActiveSupport::Concern
:
module MyExtension
extend ActiveSupport::Concern
def foo
end
module ClassMethods
def bar
end
end
end
ActiveRecord::Base.send(:include, MyExtension)
[编辑]来自@daniel的评论
然后,您的所有模型将包含作为实例方法的foo
方法, ClassMethods
的方法包含为类方法。 例如,在FooBar < ActiveRecord::Base
您将拥有: FooBar.bar
和FooBar#foo
http://api.rubyonrails.org/classes/ActiveSupport/Concern.html
链接地址: http://www.djcxy.com/p/56893.html上一篇: Rails extending ActiveRecord::Base
下一篇: Advantages of managing asset loading via AVAsset vs AVPlayerItem?