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.
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
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