How do I convert a string to a class method?

后端 未结 4 914
遇见更好的自我
遇见更好的自我 2020-12-13 04:19

This is how to convert a string to a class in Rails/Ruby:

p = \"Post\"
Kernel.const_get(p)
eval(p)
p.constantize

But what if I am retrievin

4条回答
  •  失恋的感觉
    2020-12-13 04:42

    While eval can be a useful tool for this sort of thing, and those from other backgrounds may take to using it as often as one might a can opener, it's actually dangerous to use so casually. Eval implies that anything can happen if you're not careful.

    A safer method is this:

    on_class = "Post"
    on_class.constantize.send("method_name")
    on_class.constantize.send("method_name", arg1)
    

    Object#send will call whatever method you want. You can send either a Symbol or a String and provided the method isn't private or protected, should work.

提交回复
热议问题