Calling methods a la Object#send, but not breaking when given a nonexistent method (Ruby)

351 views Asked by At

I'm trying to do something like this in Ruby with the send method:

class Foo
  def bar
    puts "Foo's bar method"
  end
end

foo = Foo.new
foo.send :bar # => "Foo's bar method"
foo.send :baz # => NoMethodError: undefined method `baz' for #<Foo:0x00000000a2e720>
              # Is there a way I can send :baz to foo without the program breaking?
              # I.e., don't call anything if the given method doesn't exist.

Obviously, passing in the nonexistent :baz returns an error, but I'm wondering if there's a way to call methods that do exist, in a send-like way, and for methods passed in that don't exist, I'm just wanting the program not to break. Does anyone know of something that does that?

2

There are 2 answers

0
Andrew Kozin On BEST ANSWER

You can use method_missing

def respond_to_missing?(*)
  true
end

private

def method_missing(*)
end

This will make your object to return nil in response to any undefined method.

For more powerful way to implement kind of NullObject pattern take look at the naught gem by Avdi Grimm.

0
ABMagil On

If you're using Rails, you might try looking at try