Reputation: 527
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.
Upvotes: 0
Views: 1208
Reputation: 497
This is possible duplicate of Given a class, see if instance has method (Ruby)
From the link above: You can use this:
User.method_defined?('name')
# => true
As other suggest, you might want to look at method missing:
class User
def name
"my name"
end
def method_missing(method, *args, &block)
puts "You called method #{method} using argument #{args.join(', ')}"
puts "--You also using block" if block_given?
end
end
User.new.last_name('Saverin') { 'foobar' }
# => "You called last_name using argument Saverin"
# => "--You also using block"
In case you don't know about ruby metaprogramming, you can start from here
Upvotes: 1
Reputation: 6411
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
Upvotes: 1