Rails扩展ActiveRecord :: Base [英] Rails extending ActiveRecord::Base
问题描述
我已经阅读了一些有关如何扩展ActiveRecord:Base类的内容,因此我的模型将具有一些特殊的方法.扩展它的简单方法是什么(逐步教程)?
I've done some reading about how to extend ActiveRecord:Base class so my models would have some special methods. What is the easy way to extend it (step by step tutorial)?
推荐答案
有几种方法:
有关详细信息,请阅读 ActiveSupport :: Concern 文档.
Read the ActiveSupport::Concern documentation for more details.
在lib
目录中创建一个名为active_record_extension.rb
的文件.
Create a file called active_record_extension.rb
in the lib
directory.
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
的文件,并将以下行添加到该文件中:
Create a file in the config/initializers
directory called extensions.rb
and add the following line to the file:
require "active_record_extension"
继承(首选)
请参阅Toby的答案.
在config/initializers
目录中创建一个名为active_record_monkey_patch.rb
的文件.
Create a file in the config/initializers
directory called 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 关于正则表达式的著名报价可以重新使用来说明与猴子修补相关的问题.
The famous quote about Regular expressions by Jamie Zawinski can be re-purposed to illustrate the problems associated with monkey-patching.
有些人在遇到问题时会想:我知道,我会用 猴子修补."现在他们有两个问题.
Some people, when confronted with a problem, think "I know, I'll use monkey patching." Now they have two problems.
猴子修补非常简单快捷.但是,节省的时间和精力总是可以提取回来的 将来的某个时候;复利.这些天来,我限制了猴子修补程序,以便在Rails控制台中快速创建解决方案的原型.
Monkey patching is easy and quick. But, the time and effort saved is always extracted back sometime in the future; with compound interest. These days I limit monkey patching to quickly prototype a solution in the rails console.
这篇关于Rails扩展ActiveRecord :: Base的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!