Module: Hyperactive::Hooker

Defined in:
lib/hyperactive/hooker.rb

Overview

A utility method to simplify using around-hooks for any block.

Class Method Summary collapse

Class Method Details

.call_with_hooks(argument, *hooks, &block) ⇒ Object

Will call each hook in hooks with a block that calls the rest of the hooks with argument as argument and after that yields to the given block.

This will allow you wrap any method call in a dynamic set of other methods.

For more examples, see Hyperactive::Record.

Example:

class ImportantStuff
  attr_accessor :timestamp
  def is_valid?
    # do nifty stuff
  end
  def notify_someone_that_i_am_changed!(message)
    # do even more nifty stuff
  end
  def validate_and_notify(message)
    raise "i am invalid!" unless is_valid?
    yield
    notify_someone_that_i_am_changed!(message)
  end
  def do_save
    # save me in persistent storage
  end
end
class ImportantHandler
  def update_timestamp(important_stuff_instance)
    important_stuff_instance.timestamp = Time.now
    Hyperactive::Hooker.call_with_hooks("changed at #{Time.now}", 
                                        important_stuff_instance.method(:validate_and_notify)) do
      important_stuff_instance.do_save
    end
  end
end


64
65
66
67
68
69
70
71
72
73
74
# File 'lib/hyperactive/hooker.rb', line 64

def call_with_hooks(argument, *hooks, &block)
  if hooks.empty?
    yield
  else
    first = hooks.first
    rest = hooks[1..-1]
    first.call(argument) do
      call_with_hooks(argument, *rest, &block)
    end
  end
end