Skip to content

Instantly share code, notes, and snippets.

@timruffles
Last active August 29, 2015 14:13
Show Gist options
  • Save timruffles/4f1821b80843b987dee8 to your computer and use it in GitHub Desktop.
Save timruffles/4f1821b80843b987dee8 to your computer and use it in GitHub Desktop.
record calls
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