Module: Surrogate::ClassMethods

Defined in:
lib/surrogate/endower.rb

Overview

use a module so that the method is inherited (important for substitutability)

Instance Method Summary collapse

Instance Method Details

#cloneObject

Should this be dup? (dup seems to copy singleton methods) and may be able to use #initialize_copy to reset ivars Can we just remove this feature an instead provide a reset feature which could be hooked into in before/after blocks (e.g. github.com/rspec/rspec-core/blob/622505d616d950ed53d12c6e82dbb953ba6241b4/lib/rspec/core/mocking/with_rspec.rb)



83
84
85
86
87
88
89
90
91
92
# File 'lib/surrogate/endower.rb', line 83

def clone
  hatchling, hatchery, parent_name = @hatchling, @hatchery, name
  Class.new self do
    extend Module.new { define_method(:name) { parent_name && parent_name + '.clone' } } # inherit the name -- use module so that ApiComparison comes out correct (real classes inherit their name method)
    Surrogate.endow self do
      hatchling.api_methods.each { |name, options| define name, options.to_hash, &options.default_proc }
    end
    hatchery.api_methods.each { |name, options| define name, options.to_hash, &options.default_proc }
  end
end

#inspectObject



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/surrogate/endower.rb', line 112

def inspect
  return name if name
  methods = SurrogateClassReflector.new(self).methods
  method_inspections = []

  # add class methods
  if methods[:class][:api].any?
    meth_names = methods[:class][:api].to_a.sort.take(4)
    meth_names[-1] = '...' if meth_names.size == 4
    method_inspections << "Class: #{meth_names.join ' '}"
  end

  # add instance methods
  if methods[:instance][:api].any?
    meth_names = methods[:instance][:api].to_a.sort.take(4)
    meth_names[-1] = '...' if meth_names.size == 4
    method_inspections << "Instance: #{meth_names.join ' '}"
  end

  # when no class or instance methods
  method_inspections << "no api" if method_inspections.empty?

  "AnonymousSurrogate(#{method_inspections.join ', '})"
end

#last_instanceObject



103
104
105
# File 'lib/surrogate/endower.rb', line 103

def last_instance
  Thread.current["surrogate_last_instance_#{self.object_id}"]
end

#last_instance=(instance) ⇒ Object



107
108
109
# File 'lib/surrogate/endower.rb', line 107

def last_instance=(instance)
  Thread.current["surrogate_last_instance_#{self.object_id}"] = instance
end

#new(*args) ⇒ Object

Custom new, because user can define initialize, and we need to record it



95
96
97
98
99
100
101
# File 'lib/surrogate/endower.rb', line 95

def new(*args)
  instance = allocate
  self.last_instance = instance
  instance.instance_variable_set :@hatchling, Hatchling.new(instance, @hatchery)
  instance.__send__ :initialize, *args
  instance
end