Class: RR::Injections::SingletonMethodAddedInjection

Inherits:
Injection
  • Object
show all
Defined in:
lib/rr/injections/singleton_method_added_injection.rb

Instance Attribute Summary

Attributes inherited from Injection

#subject

Instance Method Summary collapse

Methods inherited from Injection

#subject_has_method_defined?, #subject_has_original_method?

Methods included from Space::Reader

#space

Constructor Details

#initialize(subject) ⇒ SingletonMethodAddedInjection

Returns a new instance of SingletonMethodAddedInjection.



4
5
6
7
# File 'lib/rr/injections/singleton_method_added_injection.rb', line 4

def initialize(subject)
  @subject = subject
  @placeholder_method_defined = false
end

Instance Method Details

#bindObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rr/injections/singleton_method_added_injection.rb', line 9

def bind
  unless subject.respond_to?(original_method_alias_name)
    unless subject.respond_to?(:singleton_method_added)
      @placeholder_method_defined = true
      subject_class.class_eval do
        def singleton_method_added(method_name)
          super
        end
      end
    end

    memoized_subject = subject
    memoized_space = space
    memoized_original_method_alias_name = original_method_alias_name
    subject_class.__send__(:alias_method, original_method_alias_name, :singleton_method_added)
    subject_class.__send__(:define_method, :singleton_method_added) do |method_name_arg|
      if memoized_space.double_injection_exists?(memoized_subject, method_name_arg)
        memoized_space.double_injection(memoized_subject, method_name_arg).send(:deferred_bind_method)
      end
      send(memoized_original_method_alias_name, method_name_arg)
    end
  end
  self
end

#resetObject



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rr/injections/singleton_method_added_injection.rb', line 34

def reset
  if subject_has_method_defined?(original_method_alias_name)
    memoized_original_method_alias_name = original_method_alias_name
    placeholder_method_defined = @placeholder_method_defined
    subject_class.class_eval do
      remove_method :singleton_method_added
      unless placeholder_method_defined
        alias_method :singleton_method_added, memoized_original_method_alias_name
      end
      remove_method memoized_original_method_alias_name
    end
  end
end