Class: Surrounded::Context::Negotiator

Inherits:
Object
  • Object
show all
Includes:
Surrounded
Defined in:
lib/surrounded/context/negotiator.rb

Constant Summary

Constants included from Surrounded

VERSION

Class Method Summary collapse

Methods included from Surrounded

version

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth) ⇒ Object (private)



60
61
62
# File 'lib/surrounded/context/negotiator.rb', line 60

def method_missing(meth, ...)
  @object.send(meth, ...)
end

Class Method Details

.for_role(mod) ⇒ Object

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.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/surrounded/context/negotiator.rb', line 8

def for_role(mod)
  klass = Class.new(self)
  # Define access to the provided module
  klass.send(:define_method, :__behaviors__) do
    mod
  end
  # For each method in the module, directly forward to the wrapped object to
  # circumvent method_missing
  mod.instance_methods(false).each do |meth|
    klass.class_eval <<~MOD, __FILE__, __LINE__ + 1
      def #{meth}(...)
        @#{meth}_method ||= __behaviors__.instance_method(:#{meth}).bind(@object)
        @#{meth}_method.call(...)
      end
    MOD
  end
  klass
end