I am creating a code that is supposed to run in different environments (with a small difference in code each). The same class might define a method in one but not in the other. That way, I can use something like:
rescue NoMethodError
to catch the event when the method is not defined in one particular class, but catching exceptions is not a right logic flux.
Does it exist an alternative, something like present to know if the method is defined in a particular class? This class is a service, not an ActionController
I was thinking in something like:
class User
def name
"my name"
end
end
And then
User.new.has_method?(name)
Or something similar.
As shown here: https://ruby-doc.org/core-2.7.0/Object.html#method-i-respond_to-3F it is a method on Object. So it will check any object for that method and reply with true
or false
.
class User
def name
"my name"
end
end
User.new.respond_to?(name)
will return true
Rails has a method try
that can attempt to use a method but won't throw an error if the method doesn't exist for that object.
@user = User.first
#=> <#User...>
@user.try(:name)
#=> "Alex"
@user.try(:nonexistant_method)
#=> nil
You may also be looking for something like method_missing
, check out this post about it: https://www.leighhalliday.com/ruby-metaprogramming-method-missing