Sha256: 9cab57b8e032d950c5fe65860691f9035f6a35d402334f1ed3032be86a64728b

Contents?: true

Size: 1.41 KB

Versions: 3

Compression:

Stored size: 1.41 KB

Contents

module Surrounded
  module Context
    class Negotiator
      class << self
        # Return a class which has methods defined to forward the method to
        # the wrapped object delegating to the behavior module.
        # This prevents hits to method_missing.
        def for_role(mod)
          klass = Class.new(self)
          mod.instance_methods(false).each do |meth|
            num = __LINE__; klass.class_eval %{
              def #{meth}(*args, &block)
                @behaviors.instance_method(:#{meth}).bind(@object).call(*args, &block)
              end
            }, __FILE__, num
          end
          klass
        end
      end


      identity = "__send__|object_id"

      # Remove all methods except the identity methods
      instance_methods.reject{ |m|
        m.to_s =~ /#{identity}/
      }.each do |meth|
        undef_method meth
      end

      private

      def initialize(object, behaviors)
        @object, @behaviors = object, behaviors
      end

      def method_missing(meth, *args, &block)
        @object.send(meth, *args, &block)
      end

      def respond_to_missing?(meth, include_private=false)
        @object.respond_to?(meth, include_private)
      end
    end

    # The method_missing definition from Surrounded will apply
    # before the one defined above. This allows the methods for
    # the objects in the context to work properly
    Negotiator.send(:prepend, Surrounded)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
surrounded-0.9.4 lib/surrounded/context/negotiator.rb
surrounded-0.9.3 lib/surrounded/context/negotiator.rb
surrounded-0.9.2 lib/surrounded/context/negotiator.rb