Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before_methods and After_method callbacks in Ruby

I need to add some before_methods and after_methods to some Ruby code. What is the best way of doing this?

I've seen solutions like:

  • Ruby: automatically wrapping methods in event triggers
  • Rack::Callbacks
  • ActiveSupport::Callbacks

But they don't satisfy my needs. I am looking for an alternative that doesn't modify the existing methods.

Basically I need a way to excecute some code after/before certian method is called.

class User
  after :some_method, call: :other_method

  def some_method
    ....
  end

  def other_method
    puts "Matz"
  end
end

Thanks in advance :)

If you need a bit more explanation just let me know.

like image 589
rogeliog Avatar asked Jun 11 '26 03:06

rogeliog


1 Answers

class User
  def some_method
    puts "some method"
  end
end

set_trace_func proc { |event, file, line, id, binding, classname|
  printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}

user = User.new
user.some_method

#=> 
c-return test.rb:9  set_trace_func   Kernel
    line test.rb:11                    
  c-call test.rb:11        new    Class
  c-call test.rb:11 initialize BasicObject
c-return test.rb:11 initialize BasicObject
c-return test.rb:11        new    Class
    line test.rb:12                    
    call test.rb:2  some_method     User
    line test.rb:3  some_method     User
  c-call test.rb:3        puts   Kernel
  c-call test.rb:3        puts       IO
  c-call test.rb:3       write       IO
some methodc-return test.rb:3       write       IO
  c-call test.rb:3       write       IO

c-return test.rb:3       write       IO
c-return test.rb:3        puts       IO
c-return test.rb:3        puts   Kernel
  return test.rb:4  some_method     User

You can change the proc to print only information about User's methods.

like image 175
megas Avatar answered Jun 14 '26 06:06

megas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!