0

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.

Eduardo
  • 517
  • 5
  • 9
  • Do you mean like `some_object.respond_to?(:some_method)` ? – Beartech Mar 10 '20 at 01:29
  • Or for class methods: `SomeClass.respond_to?(:some_method)` – Beartech Mar 10 '20 at 01:30
  • Well, in apidock.com/rails/ActionController/MimeResponds/respond_to they mention its use, but it is not for controllers only? or How to use it in this case? I am working on services btw, Not in an ActionController – Eduardo Mar 10 '20 at 01:51
  • I have no idea if it will work for you since you haven't posted any of your code. Please read the question guidelines and show your code and use cases. – Beartech Mar 10 '20 at 01:54
  • And `respond_to?` is a method in Ruby, so no it is not just for views. It can be used anywhere. – Beartech Mar 10 '20 at 02:15

2 Answers2

1

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

Beartech
  • 6,173
  • 1
  • 18
  • 41
1

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

KSD Putra
  • 487
  • 2
  • 7