Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method only if it exists

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

like image 231
Frans Avatar asked Apr 03 '13 12:04

Frans


2 Answers

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.

like image 81
Aleksei Matiushkin Avatar answered Nov 09 '22 10:11

Aleksei Matiushkin


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
like image 18
jmarceli Avatar answered Nov 09 '22 12:11

jmarceli