Is there some hidden Ruby/Rails-magic for simply calling a method only if it exists?
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
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 try
is used (resource.try(:phone_number)
).
If you are not satisfied with the standard ruby syntax for that, you are free to:
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.
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:
resource.phone_number if defined? resource.phone_number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With