user3868832 user3868832 - 6 months ago 31
Ruby Question

Ruby on Rails, including a module with arguments

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

Answer

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."

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.