Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instance of class in module via string

Tags:

ruby

Say I have this Ruby code in test.rb

module MyModule
  class TestClassA
  end

  class TestClassB
    def initialize
      a = Object.const_get('MyModule::TestClassA').new
    end
  end
end

Here some tests in a ruby shell started with irb -r test.rb:

ruby-1.8.7-p302 > MyModule
 => MyModule 
ruby-1.8.7-p302 > MyModule::TestClassA
 => MyModule::TestClassA 
ruby-1.8.7-p302 > MyModule::TestClassA.new
 => #<MyModule::TestClassA:0x10036bef0> 
ruby-1.8.7-p302 > MyModule::TestClassB
 => MyModule::TestClassB 
ruby-1.8.7-p302 > MyModule::TestClassB.new
NameError: wrong constant name MyModule::TestClassA
    from ./test.rb:7:in `const_get'
    from ./test.rb:7:in `initialize'
    from (irb):1:in `new'
    from (irb):1

Why does Object.const_get('MyModule::TestClassA').new in the constructor of TestClassB fail while MyModule::TestClassA.new works in the console? I also tried Object.const_get('TestClassA').new, but that doesn't work either.

like image 905
StefanS Avatar asked May 23 '11 19:05

StefanS


1 Answers

There is no constant named "MyModule::TestClassA", there's a constant named TestClassA inside a constant named MyModule.

Try:

module MyModule
  class TestClassA
  end

  class TestClassB
    def initialize
      a = Object.const_get("MyModule").const_get("TestClassA").new
    end
  end
end

As to why it doesn't work, it's because :: is an operator and not a naming convention.

Additional examples and information is available at http://www.ruby-forum.com/topic/182803

like image 148
Simon Stender Boisen Avatar answered Nov 05 '22 06:11

Simon Stender Boisen