module SafeMonkeyPatching::Behavior

Constants

ERROR_LOCATION

Public Class Methods

add_gem_with_patch(path) click to toggle source
# File lib/safe_monkey_patching.rb, line 16
def add_gem_with_patch(path)
  @gem_paths ||= []
  @gem_paths << path
end
gems_with_patches() click to toggle source
# File lib/safe_monkey_patching.rb, line 12
def gems_with_patches
  (@gem_paths || []).uniq
end
load_store(path) click to toggle source
# File lib/safe_monkey_patching.rb, line 4
def load_store(path)
  begin
    YAML.load_file(path)
  rescue Errno::ENOENT
    {}
  end
end

Public Instance Methods

monkey_patch(method_sym) click to toggle source
# 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.deep_merge(method_entry)
  File.open(File.join(gem_path, 'monkey_patches-new.yml'), 'w') do |f|
    f.puts(new_database.to_yaml)
  end
end