Skip to content

Instantly share code, notes, and snippets.

@benschwarz
Created May 24, 2009 12:07
Show Gist options
  • Save benschwarz/117076 to your computer and use it in GitHub Desktop.
Save benschwarz/117076 to your computer and use it in GitHub Desktop.
# Usage
require 'hookr'
class A
include Hookr
def b
puts "bee"
end
before :b do
puts "aye"
end
after :b do
puts "cee"
end
end
>> A.new.b
=> "aye"
=> "bee"
=> "cee"
module Hookr
module ClassMethods
def before(target, &block)
add_hook(:before, target, block)
end
def after(target, &block)
add_hook(:after, target, block)
end
private
def add_hook(hook, target, block)
name = "_#{target}_#{hook}"
alias_method name, target
private target
define_method(target) do |*args|
block.call if hook == :before
send(name)
block.call if hook == :after
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment