Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 756
user3868832 Avatar asked Nov 16 '14 19:11

user3868832


1 Answers

There is a trick: making a class that's inheriting from a module so that you could pass any arguments to the module like class.

class Assetable < Module
  def initialize(num)
    @num = num
  end

  def included(base)
    num = @num

    base.class_eval do
      num.times do |i|
        attr_accessor "asset_#{i}"
      end
    end
  end
end

class A
  include Assetable.new(3)
end

a = A.new
a.asset_0 = 123
a.asset_0 # => 123

The details are blogged at http://kinopyo.com/en/blog/ruby-include-module-with-arguments, hope you'll find it useful.

like image 55
kinopyo Avatar answered Oct 09 '22 07:10

kinopyo