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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With