Module: AIPP::Patcher

Included in:
Parser
Defined in:
lib/aipp/patcher.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
7
# File 'lib/aipp/patcher.rb', line 4

def self.included(base)
  base.extend(ClassMethods)
  base.class_variable_set(:@@patches, {})
end

Instance Method Details

#attach_patchesObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/aipp/patcher.rb', line 19

def attach_patches
  verbose_info_method = method(:verbose_info)
  self.class.patches[self.class]&.each do |(klass, attribute, block)|
    klass.instance_eval do
      alias_method :"original_#{attribute}=", :"#{attribute}="
      define_method(:"#{attribute}=") do |value|
        error = catch :abort do
          value = block.call(self, value)
          verbose_info_method.call("Patching #{self.inspect} with #{attribute}=#{value.inspect}", color: :magenta)
        end
        fail "patching #{self.inspect} with #{attribute}=#{value.inspect} failed: #{error}" if error
        send(:"original_#{attribute}=", value)
      end
    end
  end
  self
end

#detach_patchesObject



37
38
39
40
41
42
43
44
45
46
# File 'lib/aipp/patcher.rb', line 37

def detach_patches
  self.class.patches[self.class]&.each do |(klass, attribute, _)|
    klass.instance_eval do
      remove_method :"#{attribute}="
      alias_method :"#{attribute}=", :"original_#{attribute}="
      remove_method :"original_#{attribute}="
    end
  end
  self
end