ruby convert class name in string to actual class

后端 未结 6 1761
后悔当初
后悔当初 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:39
    "Object".constantize # => Object
    
    0 讨论(0)
  • 2020-12-12 20:41

    I think what you want is constantize

    That's an RoR construct. I don't know if there's one for ruby core

    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2020-12-12 20:43

    If you want to convert string to actuall class name to access model or any other class

    str = "group class"
    
    > str.camelize.constantize 'or'
    > str.classify.constantize 'or'
    > str.titleize.constantize
    
    Example :
      def call_me(str)
        str.titleize.gsub(" ","").constantize.all
      end
    
    Call method : call_me("group class")
    
    Result:
      GroupClass Load (0.7ms) SELECT `group_classes`.* FROM `group_classes`
    
    0 讨论(0)
  • 2020-12-12 20:51

    When ActiveSupport is available (e.g. in Rails): String#constantize or String#safe_constantize, that is "ClassName".constantize.

    In pure Ruby: Module#const_get, typically Object.const_get("ClassName").

    In recent rubies, both work with constants nested in modules, like in Object.const_get("Outer::Inner").

    0 讨论(0)
  • 2020-12-12 20:53

    Given a string, first call classify to create a class name (still a string), then call constantize to try to find and return the class name constant (note that class names are constants).

    some_string.classify.constantize
    
    0 讨论(0)
提交回复
热议问题