1

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?

4
  • 3
    "is there a better way to achieve what i'm trying to do" - And what exactly are you trying to achieve by this? Commented Sep 4, 2013 at 17:14
  • Do you want the methods of the given module to be available for the specific object you're creating or for all objects of the class? Commented Sep 4, 2013 at 17:17
  • @SergioTulentsev Apologies if the code above is too abstract. I'm trying to load in class initialize settings from hashes stored in rb files. In more detail, i'm doing a Yeoman style scaffolding shell script for study purposes, i want to initialize calling the scaffolding modules required with parameters passed in when calling the script. Commented Sep 4, 2013 at 17:19
  • @sepp2k just the specific object is ok Commented Sep 4, 2013 at 17:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I see, my code has not gotten to the include line. Still the issue is on the require statement. i'd like to just require the modules i need for the specific instance that will be made
@GeorgeAnandaEman Your code has gotten to the include line and then it choked because include is not defined for plain objects. Unless I misunderstood something, using extend instead will give you the results that you want.
2
require_relative "#{f}"

Note the quotation marks. '#{f}' is not interpolated.

1 Comment

true. fixed my question so this wont get in the way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.