Callbacks are executable things, like a
Proc or methods in Ruby, whereas a hook is usually a spot in your code where you want to execute a certain subset of callbacks.
Or, precisely, callbacks that are associated to the hook.
I have lots of these places throughout my libraries, and after playing around with
ActiveSupport::Callbacks (both 2.3 and 3.0) I wrote a minimal gem to do exactly that:
Declaratively define hooks, add callbacks and run them with the options you like.
Let’s see how it works. First, install hooks.
$ gem install hooks
Usually you’d define hooks declaratively in your class.
class Coder include Hooks define_hook :after_work
You’re now ready to add callbacks, as your class now has a
Class.after_work method. Nothing more.
class Coder after_work do puts "Yeah!" end
Instance methods are also callback’able.
after_work :have_a_beer def have_a_beer puts "One for me, one for Michał!" end
Now, run a hook somewhere in your code.
def finish cleanup! run_hook :after_work end
The callbacks will be invoked in the order you added them. Sweet.
Running a hook with arguments
If you need objects in your callbacks, just pass ’em.
run_hook :at_work, self, Time.now
And be sure to equip your callbacks with the right parameters.
at_work do |who, when| ... end
So, basically a filter as found in Rails controllers is a hook. You – the user – use
Controller.after_login to add callbacks. And somewhere in the Rails core, there’d be a call to
run_hook :after_login, self
…if they’d be using hooks.