有几种方法:
使用 ActiveSupport::Concern(首选)
阅读ActiveSupport::关注 http://api.rubyonrails.org/classes/ActiveSupport/Concern.html文档以获取更多详细信息。
创建一个名为active_record_extension.rb
in the lib
目录。
require 'active_support/concern'
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"
继承(首选)
参考托比的answer https://stackoverflow.com/questions/2328984/rails-extending-activerecordbase/2330533#2330533.
猴子补丁(应该避免)
在中创建一个文件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
关于正则表达式的著名引言杰米·扎温斯基 http://regex.info/blog/2006-09-15/247可以重新调整用途来说明与猴子修补相关的问题。
有些人在遇到问题时会想:“我知道,我会用
猴子修补。”现在他们有两个问题。
猴子修补既简单又快捷。但是,节省下来的时间和精力总能收回来
将来的某个时候;以复利计算。这些天我限制猴子修补以在 Rails 控制台中快速构建解决方案原型。