Easy Callbacks
Provides callback support for Ruby classes.
Example
For a given class:
class SomeClass
def some_method(some_arg)
puts "some_method: #{some_arg}"
end
def before_some_method(some_arg)
puts "before_some_method: #{some_arg}"
end
def around_some_method(some_arg)
puts "around_some_method: #{some_arg}"
end
end
EasyCallbacks.configure(SomeClass) do
# named callback
before :some_method, :before_some_method
# named callback
around :some_method, :around_some_method
# anonymous callback
after :some_method do
puts "after_some_method: #{call_args[0]}"
end
end
This call:
SomeClass.new.some_method :some_arg
Produces this output:
before_some_method: hue
some_method: hue
around_some_method: hue
after_some_method: hue
Helper Methods
Inside a callback block/method, you can call three helper methods:
call_args # returns original arguments given to the call
call_block # returns original block given to the call
callback_details # returns details of callback execution
Callback Details
The ‘callback_details` helper method will return:
{
target_class: SomeClass,
callback_type: :around,
target_method_name: :some_method,
callback_method_name: :around_some_method,
callback_block: nil,
return_type: :success, # exclusive for `around` callbacks
return_object: nil # exclusive for `around` callbacks
}
Module inclusion
You can call ‘before`, `around` and `after` methods directly instead of calling them inside of `EasyCallbacks.configure` block. Just include `EasyCallbacks` module:
class SomeClass
def some_method(some_arg)
puts "some_method: #{some_arg}"
end
def before_some_method(some_arg)
puts "before_some_method: #{some_arg}"
end
def around_some_method(some_arg)
puts "around_some_method: #{some_arg}"
end
include EasyCallbacks
before :some_method, :before_some_method
around :some_method, :around_some_method
after :some_method do
puts "after_some_method: #{call_args[0]}"
end
end
Singleton Classes Support
It works too:
class SomeClass
class << self
def some_method(some_arg)
puts "some_method: #{some_arg}"
end
def before_some_method(some_arg)
puts "before_some_method: #{some_arg}"
end
def around_some_method(some_arg)
puts "around_some_method: #{some_arg}"
end
include EasyCallbacks
before :some_method, :before_some_method
around :some_method, :around_some_method
after :some_method do
puts "after_some_method: #{call_args[0]}"
end
end
end
SomeClass.some_method :hue
More
To see more of ‘EasyCallbacks` usages, please take a look at DummyClass.
<img src=“https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif” alt=“Donate” />