Module: Spy::Instance::API::Internal

Defined in:
lib/spy/instance/api/internal.rb

Overview

The API we expose internally to our collaborators

Instance Method Summary collapse

Instance Method Details

#attach_to(target) ⇒ Object

TODO: Not sure if this is the best place for this

Defines the spy on the target object



11
12
13
14
15
16
17
18
19
# File 'lib/spy/instance/api/internal.rb', line 11

def attach_to(target)
  spy = self
  target.class_eval do
    define_method spy.original.name do |*args, &block|
      spy.call(self, *args, &block)
    end
    send(spy.visibility, spy.original.name)
  end
end

#call(receiver, *args, &block) ⇒ Object

Call the spied method using the given receiver and arguments.

receiver is required to allow calling of UnboundMethods such as instance methods defined on a Class



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/spy/instance/api/internal.rb', line 25

def call(receiver, *args, &block)
  # TODO - abstract the method call into an object and cache this in
  #   method using an instance variable instead of a local variable.
  #   This will let us be a bit more elegant about how we do before/after
  #   callbacks. We can also merge MethodCall with this responsibility so
  #   it isn't just a data struct
  is_active = @conditional_filters.all? {|f| f.call(*args)}

  if !is_active
    call_original(receiver, *args, &block)
  else
    @before_callbacks.each {|f| f.call(*args)}

    if @around_procs.any?
      # Procify the original call
      # Still return the result from it
      result = nil
      original_proc = Proc.new do
        result = call_and_record(receiver, *args, &block)
      end

      # Keep wrapping the original proc with each around_proc
      @around_procs.reduce(original_proc) do |p, wrapper|
        Proc.new { wrapper.call receiver, *args, &p }
      end.call
    else
      result = call_and_record(receiver, *args, &block)
    end

    @after_callbacks.each {|f| f.call(*args)}

    result
  end
end