How do I convert a string to a class method?

后端 未结 4 913
遇见更好的自我
遇见更好的自我 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:39
    Post.send(anything)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 04:42

    Try this:

    class Test
     def method_missing(id, *args)
       puts "#{id} - get your method name"
       puts "#{args} - get values"
     end
    end
    
    a = Test.new
    a.name('123')
    

    So the general syntax would be a.<anything>(<any argument>).

    0 讨论(0)
  • 2020-12-13 04:44

    Since this is taged as a Ruby on Rails question, I'll elaborate just a little.

    In Rails 3, assuming title is the name of a field on an ActiveRecord object, then the following is also valid:

    @post = Post.new
    method = "title"
    
    @post.send(method)                # => @post.title
    @post.send("#{method}=","New Name") # => @post.title = "New Name"
    
    0 讨论(0)
提交回复
热议问题