Ruby on Rails,包括一个带参数的模块 [英] Ruby on Rails, including a module with arguments
问题描述
有没有办法在包含 ruby 模块时使用参数?我有一个包含在许多类中的 Assetable 模块.我希望能够即时生成 attr_accessor.
Is there a way to use arguments when including a ruby module? I have a module Assetable which is included across many classes. I want to be able to generate attr_accessor's on the fly.
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
推荐答案
在包含模块时无法传递参数.最好的下一件事是定义一个类方法,让您可以在之后创建您需要的内容:
There is no way of passing arguments when including the module. The best next thing would be to define a class method that lets you create what you need afterwards:
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
以确保正确初始化.
Also be careful when overriding the included
method within a concern because it's also used by ActiveSupport::Concern
. You should call super
within the overriden method in order to ensure proper initialization.
这篇关于Ruby on Rails,包括一个带参数的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!