Module: GollyUtils::Callbacks

Defined in:
lib/golly-utils/callbacks.rb

Overview

A very simple callback mechanism for use within a single class heirarchy.

It is primiarily meant to be used as a replacement for method overriding in external subclasses; the problem with that approach being a) it's unclear with methods are required/overrides, and b) if the wrong method name is used there is no early feedback - the erronously named method will simply never be invoked and the super-method will not receive the intended modification.

It allows:

  1. A class to define named callback point.
  2. Subclasses to supply callbacks to specific points by name.
  3. Ability to run all callbacks for a given callback point.

Unlike Rails' callbacks implementation, this deliberately doesn't provide before/after/around functionality, nor a chain-like structure where the return value of one callback can affect the determinism of other callbacks being invoked.

Usage

Examples:

class Engine
  include GollyUtils::Callbacks

  define_callback :start

  def start
    puts "About to start..."
    run_callbacks :start
    puts "Running."
  end
end

class CustomEngine < Engine
  start do
    puts "---> STARTING!!!"
  end
end

CustomEngine.new.start    # => About to start...
                          # => ---> STARTING!!!
                          # => Running.

Also works in modules

module SupportsStuff
  include GollyUtils::Callbacks
  define_callback :stuff
end

class DoerOfStuff
  include SupportsStuff
  stuff{ puts 'Doing stuff!!' }
end

def stuff_machine(anything_that_supports_stuff)
  puts "I'll take anything that SupportsStuff."
  anything_that_supports_stuff.run_callbacks :stuff
  puts "See!"
end

stuff_machine DoerOfStuff.new  # => I'll take anything that SupportsStuff.
                               # => Doing stuff!!
                               # => See!

Defined Under Namespace

Modules: ClassMethods, InstanceMethods, ModuleMethods