Module: Freedom::Patch

Defined in:
lib/freedom/patch.rb

Overview

Extend a Freedom::Patch onto your monkey-patch to add behavior for checking compatibility of the patch with the module or class that you are mixing into. Freedom patches can add compatibility checking for either instance methods or class/module methods.

Note that you currently cannot define a freedom patch that defines both instance and class methods. Module.include and Method.extend do not naturally allow you to handle both.

Class Method Summary collapse

Class Method Details

.call(method_type = :instance_method) ⇒ Module

Builds a freedom patch for the given method type

This patch can safely monkey-patch a module or class and ensure that none of the methods conflict with methods already defined on the base.

Examples:

Creates a patch that adds the #quack method.

module Quacking
  extend Freedom::Patch.(:instance_method)

  def quack
    'quack'
  end
end

class Duck
  include Quacking
end

duck = Duck.new
duck.quack  #=> 'quack'

Creates a patch that adds class introspection.

module ClassIntrospection
  extend Freedom::Patch.(:class_method)

  def methods_with_owners
    methods
      .group_by { |method_name| method(method_name).owner }
  end
end

Integer.extend ClassIntrospection
Integer.methods_with_owners

56
57
58
59
60
61
62
63
# File 'lib/freedom/patch.rb', line 56

def self.call(method_type = :instance_method)
  Module.new.tap do |patch|
    case method_type
    when :class_method then define_hook(patch, :extended, method_type: :method)
    else define_hook(patch, :included, method_type: :instance_method)
    end
  end
end