In Ruby, how can I reflect on classes contained within a module?
I'm using a library that lays its library out like this:
module Lib
class A; end
class B; end
...
end
I kn开发者_高级运维ow that I can use send
on an object to "call" a method known only at runtime (e.g., foo.send(:bar, :baz_param=>42
). How can I do this at the class level?
In other words, I suspect there's a way to write something like this:
label = :Klass
MyModule.some_method(label).new
that executes, in effect, as:
MyModule::Klass.new
Am I right?
As soon as I posted the question, I had a brainwave:
const_get
Class names are treated as constants, and the method is defined for all modules, too, so the lookup scope can be restricted to that module only. Just remember to get the capitalization right:
MyModule.const_get(:Klass).new # => #<Klass:> #CORRECT
MyModule.const_get(:klass).new # => NameError: wrong constant name
精彩评论