Reputation: 3352
Im trying to dynamically require and then include modules inside a initialize method.
# file: object.rb
class Object
attr_accessor :array
def initialize array
@array = array
@array.each do |f|
require_relative "#{f}"
include f.capitalize # the method name is the same as the filename
puts @variable # property from included method
end
end
end
object = Object.new ['a','b','c']
with these module files
# file: a.rb
module A
@variable = 'string A'
end
and so on for b and c
i keep getting an error :
`block in initialize': undefined method `include'
What am i doing wrong here and is there a better way to achieve what i'm trying to do?
Upvotes: 1
Views: 1673
Reputation: 15954
require_relative "#{f}"
Note the quotation marks. '#{f}'
is not interpolated.
Upvotes: 2
Reputation: 370357
The reason that you can't call include
in initialize
like that is that include
is a method that's only defined on classes and modules, but inside of an instance method like initialize
the implicit receiver is an object of your class, not the class itself.
Since you only need the methods to be available on the newly created object, you can just use extend
instead of include
. extend
is like a per-object version of include
in that it adds the methods of the given module as singleton methods to an object rather than adding them as instance methods to a module or class.
Upvotes: 2