-
-
Save mbbx6spp/3744878 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
This file contains hidden or 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
# So you want to find out what is messing with your object somewhere deep in your stack... | |
# Behold, your on-the-fly tracer... | |
# Updated this so it break in pry which would be more useful to look at state not in arguments of called method. | |
module NotifyWhen | |
require 'pry' | |
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])) | |
binding.pry | |
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