Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: use module include in instance method of class

Tags:

module

ruby

Have a look at the code below

initshared.rb
module InitShared
  def init_shared
    @shared_obj = "foobar"
  end
end

myclass.rb

class MyClass
  def initialize()
  end
  def init
    file_name = Dir.pwd+"/initshared.rb"
    if File.file?(file_name)
      require file_name
      include InitShared
      if self.respond_to?'init_shared'
        init_shared
        puts @shared_obj
      end
    end
  end
end

The include InitShared dosn't work since its inside the method .

I want to check for the file and then include the module and then access the variables in that module.

like image 788
goutham Avatar asked Jan 26 '26 20:01

goutham


1 Answers

Instead of using Samnang's

singleton_class.send(:include, InitShared)

you can also use

extend InitShared

It does the same, but is version independent. It will include the module only into the objects own singleton class.

like image 91
Koraktor Avatar answered Jan 29 '26 13:01

Koraktor