Finbarr
Finbarr

Reputation: 32126

Ruby any way to catch messages before method_missing?

I understand that method_missing is something of a last resort when Ruby is processing messages. My understanding is that it goes up the Object hierarchy looking for a declared method matching the symbol, then back down looking for the lowest declared method_missing. This is much slower than a standard method call.

Is it possible to intercept sent messages before this point? I tried overriding send, and this works when the call to send is explicit, but not when it is implicit.

Upvotes: 2

Views: 292

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

Not that I know of.

The most performant bet is usually to use method_missing to dynamically add the method being to a called to the class so that the overhead is only ever incurred once. From then on it calls the method like any other method.

Such as:

class Foo
  def method_missing(name, str)

    # log something out when we call method_missing so we know it only happens once
    puts "Defining method named: #{name}"

    # Define the new instance method
    self.class.class_eval <<-CODE
      def #{name}(arg1)
        puts 'you passed in: ' + arg1.to_s
      end
    CODE

    # Run the instance method we just created to return the value on this first run
    send name, str
  end
end

# See if it works
f = Foo.new
f.echo_string 'wtf'
f.echo_string 'hello'
f.echo_string 'yay!'

Which spits out this when run:

Defining method named: echo_string
you passed in: wtf
you passed in: hello
you passed in: yay!

Upvotes: 5

Related Questions