Module: SafeMonkeyPatching::Behavior

Included in:
Object
Defined in:
lib/safe_monkey_patching.rb

Constant Summary collapse

ERROR_LOCATION =
File.join(where, "WRONG_MONKEY_PATCHES.txt")

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_gem_with_patch(path) ⇒ Object



16
17
18
19
# File 'lib/safe_monkey_patching.rb', line 16

def add_gem_with_patch(path)
  @gem_paths ||= []
  @gem_paths << path
end

.gems_with_patchesObject



12
13
14
# File 'lib/safe_monkey_patching.rb', line 12

def gems_with_patches
  (@gem_paths || []).uniq
end

.load_store(path) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/safe_monkey_patching.rb', line 4

def load_store(path)
  begin
    YAML.load_file(path)
  rescue Errno::ENOENT
    {}
  end
end

Instance Method Details

#monkey_patch(method_sym) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/safe_monkey_patching.rb', line 32

def monkey_patch(method_sym)
  return unless Rails.env.test?

  caller = caller_locations.first.path
  gem_path = Gem::Specification.find do |spec|
    File.fnmatch(File.join(spec.full_gem_path, '*'), caller)
  end&.full_gem_path || Rails.root

  SafeMonkeyPatching::Behavior.add_gem_with_patch(gem_path)

  method = instance_method(method_sym)
  database = SafeMonkeyPatching::Behavior.load_store(File.join(gem_path, 'monkey_patches-new.yml'))

  method_entry = { method.owner.to_s => { method.name.to_s =>
                                            { 'sha1' => Digest::SHA1.hexdigest(method.source) } } }

  new_database = database.merge(method_entry)
  File.open(File.join(gem_path, 'monkey_patches-new.yml'), 'w') do |f|
    f.puts(new_database.to_yaml)
  end
end