创建模块有哪些优点和缺点:
module Section
def self.included(base)
base.class_eval do
has_many :books
end
end
def ensure_books
return false if books <= 0
end
end
...在模块中使用ActiveRecord方法而不是直接在它们所属的类上?
模块应该用于这样的方法吗?
答案 0 :(得分:3)
最明显的优势是您可以获取共享的功能并将其放在一个位置。这只是保持代码组织和模块化的一般优势(没有双关语) - 当然,你应该这样做
使用Active Record方法不会以任何方式使这些模块特殊。
最明显的缺点是你编写的代码稍微复杂一些。您不能直接在模块中使用validates_presence_of
,因为它不会从ActiveRecord::Base
继承。 (Rails 3应该是make it easier to selectively extend your own classes/modules with bits of ActiveRecord-Functionality
相反,当您包含模型时,需要在模型类上调用Active-Record-Methods:
module FooHelper
def self.included(other)
other.send(:has_many, :foos)
end
end
所以主要的缺点是你的代码有点难以阅读。
如果您只是将单个类拆分为单独的部分并且不需要在其他地方重用代码,则可以使用通过重新打开类来工作的concerned_with
-pattern。 / p>
另一方面,如果您需要更多功能,例如扩展程序的配置参数,请考虑writing a plugin
答案 1 :(得分:0)
此代码可由模型(类)共享。