How to instantiate class from name string in Rails?

微笑、不失礼 提交于 2019-12-02 17:24:07
klass = Object.const_get "ClassName"

about class methods

class KlassExample
    def self.klass_method
        puts "Hello World from Class method"
    end
end
klass = Object.const_get "KlassExample"
klass.klass_method

irb(main):061:0> klass.klass_method
Hello World from Class method

Others may also be looking for an alternative that does not throw an error if it fails to find the class. safe_constantize is just that.

class MyClass
end

"my_class".classify.safe_constantize.new #  #<MyClass:0x007fec3a96b8a0>
"omg_evil".classify.safe_constantize.new #  nil 

You can simply convert a string and initialize a class out of it by:

klass_name = "Module::ClassName"
klass_name.constantize

To initialize a new object:

klass_name.constantize.new

I hope this turns out to be helpful. Thanks!

I'm surprised nobody is considering security and hacking in their responses. Instantiation of an arbitrary string that likely came even indirectly from user input is asking for trouble and hacking. We all should/must be whitelisting unless we're sure the string is fully controlled and monitored

def class_for(name)
  {
    "foo" => Foo,
    "bar" => Bar,
  }[name] || raise UnknownClass
end

class_for(name_wherever_this_came_from).create!(params_somehow)

How you would know the appropriate params arbitrarily without having a whitelist would be challenging but you get the idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!