Created
May 24, 2009 12:07
-
-
Save benschwarz/117076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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