Skip to content

Instantly share code, notes, and snippets.

@lsegal
Created April 7, 2010 19:22
Show Gist options
  • Save lsegal/359307 to your computer and use it in GitHub Desktop.
Save lsegal/359307 to your computer and use it in GitHub Desktop.
module Callbacks
@@callbacks = {}
def has_callback_hook(name)
@@callbacks[name] = []
class_eval <<-CLASS
def #{name}_add block
@callbacks[#{name}] << block
end
def #{name}
@callbacks[#{name}].each do |block|
block.call self
end
end
CLASS
end
end
require 'callbacks'
class TestingCallbacks
extend Callbacks
has_callback_hook :before_foo
has_callback_hook :after_foo
attr_accessor :bar
def initialize
self.bar = "baz"
end
def foo
self.before_foo
puts self.bar
self.after_foo
end
end
require 'testing_callbacks'
test = TestingCallbacks.new
test.before_foo_add lambda { |t| t.bar = "Hello!" }
test.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment