简体   繁体   中英

How do I convert a string to a class method?

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 retrieving a method from an array/active record object like:

Post.description

but it could be

Post.anything

where anything is a string like anything = "description" .

This is helpful since I want to refactor a very large class and reduce lines of code and repetition. How can I make it work?

Post.send(anything)

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.

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"

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>) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM