Class: Mocktail::RedefinesNew

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/mocktail/replaces_type/redefines_new.rb,
lib/mocktail/sorbet/mocktail/replaces_type/redefines_new.rb

Instance Method Summary collapse

Constructor Details

#initializeRedefinesNew

Returns a new instance of RedefinesNew.



5
6
7
# File 'lib/mocktail/replaces_type/redefines_new.rb', line 5

def initialize
  @handles_dry_new_call = HandlesDryNewCall.new
end

Instance Method Details

#redefine(type) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/mocktail/replaces_type/redefines_new.rb', line 9

def redefine(type)
  type_replacement = TopShelf.instance.type_replacement_for(type)

  if type_replacement.replacement_new.nil?
    type_replacement.original_new = type.method(:new)
    type.singleton_class.send(:undef_method, :new)
    handles_dry_new_call = @handles_dry_new_call
    type.define_singleton_method :new, ->(*args, **kwargs, &block) {
      if TopShelf.instance.new_replaced?(type) ||
          (type.is_a?(Class) && TopShelf.instance.of_next_registered?(type))
        handles_dry_new_call.handle(type, args, kwargs, block)
      else
        type_replacement.original_new.call(*args, **kwargs, &block)
      end
    }
    type_replacement.replacement_new = type.singleton_method(:new)
  end
end