Last active
August 29, 2015 14:13
-
-
Save timruffles/4f1821b80843b987dee8 to your computer and use it in GitHub Desktop.
record calls
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 RecordCalls | |
# usage: | |
# resque_calls = RecordCalls.on(Resque, :enqueue) | |
# resque_calls.called_with? PostTask, :hello, :*, project.id | |
# | |
# :* is a placeholder for calls, change RecordCalls.placeholder if you want a different one | |
@placeholder = :* | |
class << self | |
attr_accessor :placeholder | |
end | |
def self.on k, method | |
Recorder.new k, method | |
end | |
class Recorder | |
attr_reader :calls | |
def initialize k, method | |
@calls = [] | |
@method = method | |
this = self | |
m = @m = Module.new do | |
define_method method do |*args, &block| | |
this.calls << [args, block] | |
end | |
end | |
k.instance_eval do | |
meta = class << self; self end | |
meta.send(:include, m) | |
end | |
end | |
def off | |
method = @method | |
@m.instance_eval do | |
define_method method do |*args, &block| | |
super *args, &block | |
end | |
end | |
end | |
def find_call_like *args | |
calls.find do |actual, block| | |
actual.zip(args).all? do |(actual, expected)| | |
actual == RecordCalls.placeholder ? true : actual == expected | |
end | |
end | |
end | |
def called_with? *args | |
call = find_call_like *args | |
!(!call) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment