Skip to content

Instantly share code, notes, and snippets.

@anthonylewis
Created July 18, 2013 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anthonylewis/6026687 to your computer and use it in GitHub Desktop.
Save anthonylewis/6026687 to your computer and use it in GitHub Desktop.
An example of a method decorator in Ruby
module TrackMethods
def track(meth)
self.class_eval do
alias_method "old_#{meth}", meth
define_method meth do |*args|
puts "Calling #{meth} with #{args.join(', ')}"
self.send "old_#{meth}", *args
end
end
end
end
class Account
extend TrackMethods
def initialize(balance)
@balance = balance
end
def deposit(n)
@balance += n
puts "Balance is now #{@balance}"
end
track :deposit
end
a = Account.new(10)
a.deposit 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment