Last Updated: February 25, 2016
·
2.471K
· emadb

Method interception in Ruby

How to intercept all the calls to a method.
Consider you have a class like this:

class MyService
  def do_something
    p "i'm doing something very interesting"
  end
end

And you want to execute something before and after the execution of method do_something. How can you do that without touching the current implementation?

Reopen the class, define an alias for dosomething and rewrite dosomething to do the extra stuff.
Like this:

MyService.class_eval do
  alias :do_something_new :do_something

  def do_something
     p "i'm ready to do something"
     do_something_new
     p "i did something interesting, isn't it?"
  end
end

Now if you call do_something you'll have:

service = MyService.new
service.do_something
>> "i'm ready to do something"
>> "i'm doing something very interesting"
>> "i did something interesting, isn't it?"