Call method only if it exists

Solution 1:

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.

Solution 2:

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

Solution 3:

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

Solution 4:

I can't speak for the efficiency, but something like...

Klass.methods.include?(:method_name) 

works for me in Rails 4