Skip to content

Instantly share code, notes, and snippets.

@RobertDober
Created August 15, 2009 06:45
Show Gist options
  • Save RobertDober/168289 to your computer and use it in GitHub Desktop.
Save RobertDober/168289 to your computer and use it in GitHub Desktop.
use pattern of alias, and advice
# The pattern for using alias
alias_method :__behavior__, :behavior
remove_method :behavior
define_method :behavior do
# ...
__behavior__
# ...
end
# Does that ring some bells?
class Module
def advice_method methd, when_={}
m = method methd
remove_method methd
define_method methd do | *args, &blk |
largs = args
lblk = blk
largs, lblk = when_.fetch( :input ){ lambda{ | *a, &b | [ a, b ] } }.call( *args, &blk )
when_.fetch( :before, empty }.call( *largs, &lblk )
result = m.bind( self ).call( *largs, &lblk )
when_.fetch( :after, empty ).call( *largs, &lblk )
when_.fetch( :output ){ return result }.call( *largs, &lblk )
end
end
def around methd, before, after
adv_method methd, before: before, after: after
end
def before methd, &blk
advice_method methd, before: blk
end
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment