Class: AncientMock::Stubber

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ Stubber

Returns a new instance of Stubber.



37
38
39
40
41
# File 'lib/ancient_mock.rb', line 37

def initialize(obj)
  @obj = obj
  @definitions = []
  @preserved_methods = []
end

Class Method Details

.for_object(obj) ⇒ Object



28
29
30
# File 'lib/ancient_mock.rb', line 28

def self.for_object(obj)
  stubbers[obj.__id__] ||= Stubber.new(obj)
end

.resetObject



32
33
34
35
# File 'lib/ancient_mock.rb', line 32

def self.reset
  stubbers.each_value(&:reset)
  stubbers.clear
end

.stubbersObject



24
25
26
# File 'lib/ancient_mock.rb', line 24

def self.stubbers
  @stubbers ||= { }
end

Instance Method Details

#resetObject



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/ancient_mock.rb', line 61

def reset
  @definitions.each do |definition|
    @obj.singleton_class.class_eval do
      remove_method(definition.message) if method_defined?(definition.message)
    end
  end

  @preserved_methods.reverse.each do |method|
    @obj.define_singleton_method(method.name, method)
  end
end

#stub(definition) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ancient_mock.rb', line 43

def stub(definition)
  @definitions << definition

  # preserve the method if already exists
  if @obj.singleton_class.method_defined?(definition.message)
    @preserved_methods <<
      @obj.singleton_class.instance_method(definition.message)
  end

  definitions = @definitions
  @obj.define_singleton_method(definition.message) do |*arguments|
    definitions.
      reverse.
      find { |d| d.matches?(definition.message, *arguments) }.
      call
  end
end