Ruby-on-rails 如何将字符串转换为类方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2913566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a string to a class method?
提问by kgpdeveloper
This is how to convert a string to a class in Rails/Ruby:
这是在 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".
其中任何东西都是像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?
这很有帮助,因为我想重构一个非常大的类并减少代码行和重复。我怎样才能让它工作?
回答by shingara
Post.send(anything)
回答by Intentss
Since this is taged as a Ruby on Rails question, I'll elaborate just a little.
由于这被标记为 Ruby on Rails 问题,我将详细说明。
In Rails 3, assuming titleis the name of a field on an ActiveRecord object, then the following is also valid:
在 Rails 3 中,假设title是 ActiveRecord 对象上的字段名称,则以下内容也有效:
@post = Post.new
method = "title"
@post.send(method) # => @post.title
@post.send("#{method}=","New Name") # => @post.title = "New Name"
回答by tadman
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.
虽然 eval 可以成为这类事情的有用工具,并且来自其他背景的人可能会像开罐头一样经常使用它,但如此随意地使用实际上是危险的。Eval 意味着如果您不小心,任何事情都可能发生。
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.
Object#send 将调用您想要的任何方法。您可以发送一个 Symbol 或一个 String 并且提供该方法不是私有的或受保护的,应该可以工作。
回答by sameera207
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>).
所以一般的语法是a.<anything>(<any argument>).

