Sha256: 303b2d008018b7806ea085ad7f72eb548ad68fe97181f3797397aa429e823096

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

module Quarry

  # = Overlay
  #
  # The idea of the Overlay is to proved a convenient way to 
  # create test stubs. You can take an original class and
  # turn features on and off at your leasure, substituting
  # in your choice of code piece meal.
  #
  #   class X
  #     def a; 1; end
  #     def b; a + 1; end
  #   end
  #
  #   XO = Quarry::Overlay.new do
  #     def_over(:a) do
  #       2  
  #     end
  #   end
  #
  #   x = X.new
  #   p x.a  #=> 1
  #
  #   XO.append_features(X)
  #   p x.a  #=> 2
  #
  #   XO.remove_features(X)
  #   p x.a  #=> 1
  #
  class Overlay

    def initialize(&block)
      @over  = {}
      @cache = Hash.new{ |h,k| h[k]={} }
      instance_eval(&block) if block_given?
    end

    def define_method(methname, &block)
      @over[methname] = block
    end

    def append_features(base)
      @over.each do |name, block|
        next if base.instance_methods(true).include?("#{name}:#{base.__id__}:super")
        if m = base.instance_methods(true).include?(name.to_s)
          base.__send__(:alias_method, "#{name}:#{base.__id__}:super", name)
          base.__send__(:define_method, name, &block)
        end
      end
    end

    def remove_features(base)
      @over.each do |name, block|
        next unless base.instance_methods(true).include?("#{name}:#{base.__id__}:super")
        if m = base.instance_method("#{name}:#{base.__id__}:super")
          base.__send__(:alias_method, name, "#{name}:#{base.__id__}:super")
        end
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
quarry-0.4.0 work/deprecated/overlay.rb