Module: Docile::Execution Private

Included in:
Docile
Defined in:
lib/docile/execution.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

A namespace for functions relating to the execution of a block against a proxy object.

Class Method Summary collapse

Class Method Details

.exec_in_proxy_context(dsl, proxy_type, *args, &block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Execute a block in the context of an object whose methods represent the commands in a DSL, using a specific proxy class.

Parameters:

  • dsl (Object)

    context object whose methods make up the (initial) DSL

  • proxy_type (FallbackContextProxy, ChainingFallbackContextProxy)

    which class to instantiate as proxy context

  • args (Array)

    arguments to be passed to the block

  • block (Proc)

    the block of DSL commands to be executed

Returns:

  • (Object)

    the return value of the block



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/docile/execution.rb', line 19

def exec_in_proxy_context(dsl, proxy_type, *args, &block)
  block_context = eval("self", block.binding) # rubocop:disable Style/EvalWithLocation

  # Use #equal? to test strict object identity (assuming that this dictum
  # from the Ruby docs holds: "[u]nlike ==, the equal? method should never
  # be overridden by subclasses as it is used to determine object
  # identity")
  return dsl.instance_exec(*args, &block) if dsl.equal?(block_context)

  proxy_context = proxy_type.new(dsl, block_context)
  begin
    block_context.instance_variables.each do |ivar|
      value_from_block = block_context.instance_variable_get(ivar)
      proxy_context.instance_variable_set(ivar, value_from_block)
    end

    proxy_context.instance_exec(*args, &block)
  ensure
    if block_context.respond_to?(:__docile_undo_fallback__)
      block_context.send(:__docile_undo_fallback__)
    end

    block_context.instance_variables.each do |ivar|
      next unless proxy_context.instance_variables.include?(ivar)

      value_from_dsl_proxy = proxy_context.instance_variable_get(ivar)
      block_context.instance_variable_set(ivar, value_from_dsl_proxy)
    end
  end
end