Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created September 18, 2012 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pmarreck/3744666 to your computer and use it in GitHub Desktop.
Save pmarreck/3744666 to your computer and use it in GitHub Desktop.
NotifyWhen, a Ruby module you can extend any object with to get on-the-fly tracing of any later method calls on it
# So you want to find out what is messing with your object somewhere deep in your stack...
# Behold, your on-the-fly tracer...
module NotifyWhen
def notify_when(*meths, &callback)
class << self; self; end.instance_eval do
meths.each do |meth|
alias_method "unnotified_#{meth}".to_sym, meth
define_method(meth) do |*args, &block|
callback.yield(*([meth, args, self][0..callback.arity]))
send("unnotified_#{meth}", *args, &block)
end
end
end
end
end
h = {} # can be any object
h.extend NotifyWhen
h.notify_when(:[], :[]=){|m, args| puts "#{m} was called with args #{args}"}
h[5] = 'five'
h[5]
h[6]
# []= was called with args [5, "five"]
# [] was called with args [5]
# [] was called with args [6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment