Sha256: 565d734048bb1ebc5600f20a40be42a406516fb7da94a2a462bd4479a527adae

Contents?: true

Size: 1.07 KB

Versions: 1

Compression:

Stored size: 1.07 KB

Contents

require "surrounded/version"

module Surrounded
  def self.included(klass)
    klass.class_eval {
      extend Surrounded::Contextual
    }
    unless klass.is_a?(Class)
      def klass.extended(object)
        Surrounded.create_surroundings(object)
      end
    end
  end

  def self.extended(object)
    Surrounded.create_surroundings(object)
  end

  module Contextual
    def new(*args)
      instance = super
      Surrounded.create_surroundings(instance)
      instance
    end
  end

  def store_context(ctxt)
    surroundings.unshift(ctxt)
  end

  def remove_context
    surroundings.shift
  end

  private

  def self.create_surroundings(obj)
    obj.instance_variable_set(:@__surroundings__, [])
  end

  def surroundings
    @__surroundings__
  end

  def context
    surroundings.first || NullContext.new
  end

  def method_missing(meth, *args, &block)
    context.role?(meth){} || super
  end

  def respond_to_missing?(meth, include_private=false)
    !!context.role?(meth){} || super
  end

  class NullContext < BasicObject
    def role?(*args)
      nil
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
surrounded-0.2.0 lib/surrounded.rb