包括ruby模块时,是否可以使用参数?我有一个Assetable模块,该模块包含在许多类中。我希望能够即时生成attr_accessor。
module Assetable
extend ActiveSupport::Concern
included do
(argument).times do |i|
attr_accessor "asset_#{i}".to_sym
attr_accessible "asset_#{i}".to_sym
end
end
end
包含模块时,无法传递参数。最好的下一件事是定义一个类方法,该方法可让您随后创建所需的内容:
module Assetable
extend ActiveSupport::Concern
module ClassMethods
def total_assets(number)
number.times do |i|
attr_accessor "asset_#{i}"
attr_accessible "asset_#{i}"
end
end
end
end
class C
include Assetable
total_assets 3
end
o = C.new
o.asset_2 = "Some value."
o.asset_2 #=> "Some value."
在覆盖included
关注范围内的方法时也要小心,因为它也被所使用ActiveSupport::Concern
。您应该super
在overriden方法内调用以确保正确的初始化。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句