class ActiveSpy::SpyList

Singleton used to hold the spies and lazely active these spies by patching the methods in the specified classes.

Attributes

spies[R]

Public Class Methods

method_missing(method, *args, &block) click to toggle source

Proxy all methods called in the {ActiveSpy::SpyList} class to a {ActiveSpy::SpyList} instance. Just a syntax sugar.

# File lib/active_spy/spy/spy_list.rb, line 22
def self.method_missing(method, *args, &block)
  instance.send(method, *args, &block)
end
new() click to toggle source

Just to initiliaze the spy list.

# File lib/active_spy/spy/spy_list.rb, line 13
def initialize
  @spies = []
end

Public Instance Methods

<<(other) click to toggle source

forward {<<} method to the spy list.

# File lib/active_spy/spy/spy_list.rb, line 51
def <<(other)
  @spies << other
end
activate() click to toggle source

Activate all the spies defined in the spy list by patching the methods in their classes.

# File lib/active_spy/spy/spy_list.rb, line 29
def activate
  @spies.each do |spy|
    spied_class = spy['class']
    spied_method = spy['method']

    spy['old_method'] = patch(spied_class, spied_method) unless spy['active']
    spy['active'] = true
  end
end
deactivate() click to toggle source

Deactivate all the spies defined in the spy list by unpatching the methods in their classes.

# File lib/active_spy/spy/spy_list.rb, line 42
def deactivate
  @spies.each do |spy|
    unpatch(spy['class'], spy['method'], spy['old_method'])
    spy['active'] = nil
  end
end

Private Instance Methods

patch(klass, method) click to toggle source

This method patches the method in the class klass to invoke the callbacks defined in the respective class, that should be named using appending ‘Events’ to the class’ name, and inherites from {ActiveSpy::Base}.

# File lib/active_spy/spy/spy_list.rb, line 62
def patch(klass, method)
  old_method = nil
  ActiveSupport::Inflector.constantize(klass).class_eval do
    old_method = instance_method(method)
    define_method method do |*args, &block|
      send(:invoke_callback, method, :before)
      result = old_method.bind(self).call(*args, &block)
      if defined?(Rails)
        send(:invoke_callback, method, :after) if result
      else
        send(:invoke_callback, method, :after)
      end
      result
    end
  end
  old_method
end
unpatch(klass, method, old_method) click to toggle source

Properyly unpatch the method in class klass and put back old_method in its place.

# File lib/active_spy/spy/spy_list.rb, line 83
def unpatch(klass, method, old_method)
  ActiveSupport::Inflector.constantize(klass).class_eval do
    define_method method do |*args, &block|
      old_method.bind(self).call(*args, &block)
    end
  end
end