class Spy::Core

The main internal API. This is used directly by `Spy::API` and is the primary control center for creating and removing spies.

Syntactic sugar (like `Spy.restore(object, msg)` vs `Spy.restore(:all)`) should be handled in `Spy::API` and utilize `Spy::Core`

Constants

UNSAFE_METHODS

Public Class Methods

new() click to toggle source
# File lib/spy/core.rb, line 15
def initialize
  @registry = Registry.new
end

Public Instance Methods

add_multi_spy(multi_blueprint) click to toggle source

Start spying on all of the given objects and methods

@param [Spy::Blueprint] blueprint - data for building the spy @returns [Spy::Multi]

# File lib/spy/core.rb, line 38
def add_multi_spy(multi_blueprint)
  target = multi_blueprint.target
  type = multi_blueprint.type
  methods = target.public_send(type).reject(&method(:unsafe_method?))
  spies = methods.map do |method_name|
    singular_type = type.to_s.sub(/s$/, '').to_sym
    add_spy(Blueprint.new(multi_blueprint.target, method_name, singular_type))
  end
  Multi.new(spies)
end
add_spy(blueprint) click to toggle source

Start spying on the given object and method

@param [Spy::Blueprint] blueprint - data for building the spy @returns [Spy::Instance] @raises [Spy::Errors::AlreadySpiedError] if the method is already

being spied on
# File lib/spy/core.rb, line 25
def add_spy(blueprint)
  if prev = @registry.get(blueprint)
    raise Errors::AlreadySpiedError.new("Already spied on #{blueprint} here:\n\t#{prev[0].caller.join("\n\t")}")
  end
  spy = Instance.new(blueprint)
  @registry.insert(blueprint, spy)
  spy.start
end
remove_all_spies() click to toggle source

Stops spying on all objects and methods

# File lib/spy/core.rb, line 59
def remove_all_spies
  @registry.remove_all.each(&:stop)
end
remove_spy(blueprint) click to toggle source

Stop spying on the given object and method

@raises [Spy::Errors::MethodNotSpiedError] if the method is not already

being spied on
# File lib/spy/core.rb, line 53
def remove_spy(blueprint)
  spy = @registry.remove(blueprint)
  spy.stop
end

Private Instance Methods

unsafe_method?(name) click to toggle source
# File lib/spy/core.rb, line 65
def unsafe_method?(name)
  UNSAFE_METHODS.include?(name)
end