ruby convert class name in string to actual class

后端 未结 6 1784
后悔当初
后悔当初 2020-12-12 20:03

How do I call a class from a string containing that class name inside of it? (I guess I could do case/when but that seems ugly.)

The reason I ask is because I\'m us

6条回答
  •  悲哀的现实
    2020-12-12 20:42

    I know this is an old question but I just want to leave this note, it may be helpful for others.

    In plain Ruby, Module.const_get can find nested constants. For instance, having the following structure:

    module MyModule
      module MySubmodule
        class MyModel
        end
      end
    end
    

    You can use it as follows:

    Module.const_get("MyModule::MySubmodule::MyModel")
    MyModule.const_get("MySubmodule")
    MyModule::MySubmodule.const_get("MyModel")
    

提交回复
热议问题