Ruby-on-rails 仅在存在时调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15787610/
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
Call method only if it exists
提问by Frans
Is there some hidden Ruby/Rails-magic for simply calling a method only if it exists?
是否有一些隐藏的 Ruby/Rails-magic 仅在方法存在时才调用它?
Lets say I want to call
假设我想打电话
resource.phone_number
but I don't know beforehand if resource responds to phone_number. A way to do this is
但我事先不知道资源是否响应phone_number. 一种方法是
resource.phone_number if resource.respond_to? :phone_number
That's not all that pretty if used in the wrong place. I'm curious if something exists that works more along the lines of how tryis used (resource.try(:phone_number)).
如果在错误的地方使用,那并不是那么漂亮。我很好奇是否存在更符合try使用方式的东西(resource.try(:phone_number))。
采纳答案by Aleksei Matiushkin
If you are not satisfied with the standard ruby syntax for that, you are free to:
如果您对标准的 ruby 语法不满意,您可以自由地:
class Object
def try_outside_rails(meth, *args, &cb)
self.send(meth.to_sym, *args, &cb) if self.respond_to?(meth.to_sym)
end
end
Now:
现在:
resource.try_outside_rails(:phone_number)
will behave as you wanted.
会如你所愿。
回答by jmarceli
I would try defined?(http://ruby-doc.org/docs/keywords/1.9/Object.html#defined-3F-method). It seems to do exactly what you are asking for:
我会尝试defined?(http://ruby-doc.org/docs/keywords/1.9/Object.html#defined-3F-method)。它似乎完全符合您的要求:
resource.phone_number if defined? resource.phone_number
回答by Bhavya
I know this is very old post. But just wanted to know if this could be a possible answer and whether the impact is the same .
我知道这是很老的帖子。但只是想知道这是否是一个可能的答案以及影响是否相同。
resource.try(:phone_number) rescue nil
Thanks
谢谢
回答by Stephen
I can't speak for the efficiency, but something like...
我不能说效率,但像......
Klass.methods.include?(:method_name)
works for me in Rails 4
在 Rails 4 中对我来说有效
回答by nroose
If A.cis defined and A.aand A.bare not, you can do A.a rescue A.b rescue A.cand it will work like a charm. You will be breaking some silly rules, though.
如果A.c被定义,A.a并且A.b都没有,你可以做A.a rescue A.b rescue A.c,它会像一个魅力。不过,您将违反一些愚蠢的规则。

