Class: Spy::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/spy/instance.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(receiver, msg, method_type) ⇒ Instance

Returns a new instance of Instance.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/spy/instance.rb', line 12

def initialize(receiver, msg, method_type)
  @msg = msg
  @receiver = receiver
  @method_type = method_type
  @before_filters = []
  @call_count = 0

  # Cache the original method for unwrapping later
  @original = @receiver.send(method_type, msg)
  @visibility = extract_visibility
end

Instance Attribute Details

#call_countObject (readonly)

Returns the value of attribute call_count.



10
11
12
# File 'lib/spy/instance.rb', line 10

def call_count
  @call_count
end

#method_typeObject (readonly)

Returns the value of attribute method_type.



10
11
12
# File 'lib/spy/instance.rb', line 10

def method_type
  @method_type
end

#msgObject (readonly)

Returns the value of attribute msg.



10
11
12
# File 'lib/spy/instance.rb', line 10

def msg
  @msg
end

#originalObject (readonly)

Returns the value of attribute original.



10
11
12
# File 'lib/spy/instance.rb', line 10

def original
  @original
end

#receiverObject (readonly)

Returns the value of attribute receiver.



10
11
12
# File 'lib/spy/instance.rb', line 10

def receiver
  @receiver
end

#visibilityObject (readonly)

Returns the value of attribute visibility.



10
11
12
# File 'lib/spy/instance.rb', line 10

def visibility
  @visibility
end

Instance Method Details

#before_call(*args) ⇒ Object



49
50
51
# File 'lib/spy/instance.rb', line 49

def before_call(*args)
  @call_count += 1 if @before_filters.all? {|f| f.before_call(*args)}
end

#startObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/spy/instance.rb', line 24

def start
  context = self
  original.owner.instance_eval do
    define_method context.msg do |*args|
      context.before_call(*args)
      if context.original.respond_to? :bind
        result = context.original.bind(self).call(*args)
      else
        result = context.original.call(*args)
      end
      result
    end
    send(context.visibility, context.msg)
  end
  self
end

#stopObject



41
42
43
44
45
46
47
# File 'lib/spy/instance.rb', line 41

def stop
  context = self
  original.owner.instance_eval do
    define_method context.msg, context.original
  end
  self
end

#when(&block) ⇒ Object



57
58
59
# File 'lib/spy/instance.rb', line 57

def when(&block)
  add_before_filter Callbacks::When.new(block)
end

#with_args(*args) ⇒ Object



53
54
55
# File 'lib/spy/instance.rb', line 53

def with_args(*args)
  add_before_filter Callbacks::WithArgs.new(*args)
end