Module: Spy::API

Included in:
Spy
Defined in:
lib/spy/api.rb

Overview

The core module that users will interface. ‘Spy::API` is implemented in a module via `::extend`:

MySpy.exted Spy::API
spy = MySpy.on(Object, :name)

By default ‘Spy` implements `Spy::API`

‘Spy::API` is primarily responsible for maps user arguments into a format that `Spy::Core` can understand

See ‘Spy::Instance` for the API for interacting with individual spies

Instance Method Summary collapse

Instance Method Details

#on(target, msg) ⇒ Object

Spies on calls to a method made on a target object

Parameters:

  • target (Object)
    • the object you want to spy on

  • msg (Symbol)
    • the name of the method to spy on



23
24
25
26
27
28
29
30
31
# File 'lib/spy/api.rb', line 23

def on(target, msg)
  if target.methods.include?(msg)
    core.add_spy(Blueprint.new(target, msg, :method))
  elsif target.respond_to?(msg)
    core.add_spy(Blueprint.new(target, msg, :dynamic_delegation))
  else
    raise ArgumentError
  end
end

#on_any_instance(target, msg) ⇒ Object

Spies on calls to a method made on any instance of some class or module

Parameters:

  • target
    • class or module to spy on

  • msg
    • name of the method to spy on

Raises:

  • (ArgumentError)


38
39
40
41
# File 'lib/spy/api.rb', line 38

def on_any_instance(target, msg)
  raise ArgumentError unless target.respond_to?(:instance_method)
  core.add_spy(Blueprint.new(target, msg, :instance_method))
end

#on_class(klass) ⇒ Object

Spies on all of the calls made to the given class or module

Parameters:

  • klass
    • the thing to spy on



55
56
57
# File 'lib/spy/api.rb', line 55

def on_class(klass)
  core.add_multi_spy(Blueprint.new(klass, :all, :instance_methods))
end

#on_object(object) ⇒ Object

Spies on all of the calls made to the given object

Parameters:

  • object
    • the thing to spy on



47
48
49
# File 'lib/spy/api.rb', line 47

def on_object(object)
  core.add_multi_spy(Blueprint.new(object, :all, :methods))
end

#restore(*args) ⇒ Object

Stops spying on the method and restores its original functionality

Examples:

stop spying on every spied message


Spy.restore(:all)

stop spying on the given receiver and message


Spy.restore(receiver, msg)

stop spying on the given object, message, and type (e.g. :method, :instance_method, :dynamic_delegation)


Spy.restore(object, msg, type)

Parameters:

  • args
    • supports multiple signatures



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/spy/api.rb', line 74

def restore(*args)
  case args.length
  when 1
    core.remove_all_spies if args.first == :all
  when 2
    target, msg = *args
    core.remove_spy(Blueprint.new(target, msg, :method))
  when 3
    target, msg, type = *args
    core.remove_spy(Blueprint.new(target, msg, type))
  else
    raise ArgumentError
  end
end