In Ruby I create a module like this:
Mod = Module.new do
class MyClass
attr_reader :a
def initialize(a)
@a = a
end
end
end
And I'm trying to create an instance of the class:
puts Mod::MyClass.new(1).a
But I get an error:
(irb):10:in `<main>': uninitialized constant Mod::MyClass (NameError)
puts Mod::MyClass.new(1).a
Although that's how it works:
Mod.module_eval { puts MyClass.new(1).a }
1
=> nil
I'm also trying to make the class public:
Mod.instance_eval do
public_constant :MyClass
end
But I also get an error:
(irb):16:in `public_constant': constant Mod::MyClass not defined (NameError)
public_constant :MyClass
But if you create it like this, then everything works:
module Mod2
class MyClass
attr_reader :a
def initialize(a)
@a = a
end
end
end
puts Mod2::MyClass.new(1).a
1
=> nil
Is there a way to access Mod::MyClass without eval?
puts Mod::MyClass.new(1).a
MyClasswill work. This occurs becauseModule.new dodoes not create a proper "scope gate"class self::MyClassMod::MyClasswithouteval" – even with eval there’s noMod::MyClass. You’re merely referring to the top level class from within the module.puts Mod::MyClass.new(1).a– why are you creating an anonymous module in the first place if you're referring to it via a constant anyway? Or is this more of a conceptual question?