File: execution.rb

package info (click to toggle)
ruby-docile 1.1.5-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 156 kB
  • sloc: ruby: 374; makefile: 2
file content (35 lines) | stat: -rw-r--r-- 1,510 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
module Docile
  # @api private
  #
  # A namespace for functions relating to the execution of a block against a
  # proxy object.
  module Execution
    # Execute a block in the context of an object whose methods represent the
    # commands in a DSL, using a specific proxy class.
    #
    # @param dsl        [Object] context object whose methods make up the
    #                            (initial) DSL
    # @param proxy_type [FallbackContextProxy, ChainingFallbackContextProxy]
    #                            which class to instantiate as proxy context
    # @param args       [Array]  arguments to be passed to the block
    # @param block      [Proc]   the block of DSL commands to be executed
    # @return           [Object] the return value of the block
    def exec_in_proxy_context(dsl, proxy_type, *args, &block)
      block_context = eval('self', block.binding)
      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
        block_context.instance_variables.each do |ivar|
          value_from_dsl_proxy = proxy_context.instance_variable_get(ivar)
          block_context.instance_variable_set(ivar, value_from_dsl_proxy)
        end
      end
    end
    module_function :exec_in_proxy_context
  end
end