Class: Rys::Patcher

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

Class Method Summary collapse

Class Method Details

.add(klass_to_patch, &block) ⇒ Object


13
14
15
16
# File 'lib/rys/patcher.rb', line 13

def self.add(klass_to_patch, &block)
  patches << Patch.new(klass_to_patch, &block)
  self
end

.apply(where: nil) ⇒ Object


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rys/patcher.rb', line 26

def self.apply(where: nil)
  patches.each do |patch|
    next if patch.where != where

    klass_to_patch = patch.klass.constantize

    if patch.apply_only_once && applied_count != 0
      next
    end

    if patch.apply_if && !patch.apply_if.call
      next
    end

    patch.includeds.each do |included|
      klass_to_patch.class_eval(&included)
    end

    patch.instance_methods.each do |options, block|
      prepended_methods(klass_to_patch, options, block)
    end

    patch.class_methods.each do |options, block|
      prepended_methods(klass_to_patch.singleton_class, options, block)
    end
  end
end

.prepended_methods(klass_to_patch, options, block) ⇒ Object

TODO: What should happen if

instance_methods(feature: ...) do
  def uniq_method_which_does_not_exist_yet
  end
end

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rys/patcher.rb', line 60

def self.prepended_methods(klass_to_patch, options, block)
  mod = Rys::PatchModule.new(&block)

  if options[:feature]
    # Save original methods
    method_list = mod.instance_methods.map{|m| [m, "#{m}_#{SecureRandom.hex}"] }
    method_list.each do |m, aliased_m|
      klass_to_patch.send(:alias_method, aliased_m, m)
    end
  end

  klass_to_patch.prepend(mod)

  if options[:feature]
    mod = Rys::PatchModule.new do
      method_list.each do |m, aliased_m|
        define_method(m) do |*args, &block|
          if ::Rys::Feature.active?(options[:feature])
            super(*args, &block)
          else
            # method(__method__).super_method.super_method.call(*args, &block)
            __send__(aliased_m, *args, &block)
          end
        end
      end
    end

    klass_to_patch.prepend(mod)
  end
end

.reload_patchesObject


18
19
20
21
22
23
24
# File 'lib/rys/patcher.rb', line 18

def self.reload_patches
  patches.clear
  paths.each do |path|
    pattern = File.join(path, '**/*.rb')
    Dir.glob(pattern){|f| load(f) }
  end
end