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



22
23
24
# File 'lib/spy/api.rb', line 22

def on(target, msg)
  core.add_spy(target, target.method(msg))
end

#on_any_instance(target, msg) ⇒ Object

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

Raises:

  • (ArgumentError)


31
32
33
34
# File 'lib/spy/api.rb', line 31

def on_any_instance(target, msg)
  raise ArgumentError unless target.respond_to?(:instance_method)
  core.add_spy(target, target.instance_method(msg))
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 method type (e.g. :instance_method)


Spy.restore(object, msg, method_type)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/spy/api.rb', line 51

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