Home > Net >  Ruby: check if object has a method with particular signature, like respond_to?
Ruby: check if object has a method with particular signature, like respond_to?

Time:10-22

Is there a way to check if particular method signature is present in Ruby?

For example I want to call

thing.make(env: @@__ENV__, apiKey: "myKey")

if I do this check

if thing.respond_to? 'make'

I can end up with the error

ArgumentError: unknown keyword: :apiKey

Is there a way to check that there is the particular make(env:,apiKey:) method and not just make with any arguments

CodePudding user response:

Simplest thing to do is try it and rescue the ArgumentError.

begin
  thing.make(env: @@__ENV__, apiKey: "myKey")
rescue ArgumentError => e
  ...guess not...
end

You can also introspect the parameters of the Method object. This returns an Array of Arrays like [[:key, :env], [:key, :apiKey]] . You're looking for :key if its optional, :keyreq if it's required.

params = thing.method(:make).parameters
p [:env,:apiKey].all? { |arg|
  params.include?([:key,arg]) || params.include?([:keyreq, arg])
}

If you have to do this as part of application code, you may want to reconsider your design.

  • Related