Class: ExecEnv::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/exec_env/env.rb

Overview

A manipulatable execution environment, that let’s you inject local and instance variables into a block and capture messages sent during it’s execution.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(locals: {}, ivars: {}, scope: nil) ⇒ Env

Returns a new instance of Env.



45
46
47
48
49
50
# File 'lib/exec_env/env.rb', line 45

def initialize (locals: {}, ivars: {}, scope: nil)
  @messages = []
  @locals = locals
  @ivars = ivars
  @scope = scope
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/exec_env/env.rb', line 77

def method_missing (name, *args, &block)
  if @locals.key?(name) && args.size == 0 && !block
    @locals[name]
  elsif @scope && @scope.respond_to?(name)
    @scope.send(name, *args, &block)
  else
    @messages << [name, args, block]

    nil
  end
end

Instance Attribute Details

#ivarsObject

A hash of instance variables, that will be injected into the block

Examples

env.ivars = { :@foo => 3, :@bar => :symbol }


18
19
20
# File 'lib/exec_env/env.rb', line 18

def ivars
  @ivars
end

#localsObject

A hash of local variables, that will be injected into the block

Examples

env.locals = { foo: 3, bar: :symbol }


11
12
13
# File 'lib/exec_env/env.rb', line 11

def locals
  @locals
end

#messagesObject (readonly)

An array of all messages that were not captured by locals or the scope object.

Examples

env.exec do
  test :foo, "bar"
  each do
    # ...
  end
end

env.messages
# => [[:test, [:foo, "bar], nil], [:each, [], <the block>]]


43
44
45
# File 'lib/exec_env/env.rb', line 43

def messages
  @messages
end

#scopeObject

An object, that will serve as the scope of execution of the block

Examples

# Unresolved method calls in the block will be forwarded to
# the String object "An object"
env.scope = "An object"


27
28
29
# File 'lib/exec_env/env.rb', line 27

def scope
  @scope
end

Instance Method Details

#exec(*args, &block) ⇒ Object

Execute a block in the manipulated environment.

Additional arguments will be passed to the block.

Returns the return value of the block



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/exec_env/env.rb', line 57

def exec (*args, &block)
  if @scope
    @scope.instance_variables.each do |name|
      instance_variable_set(name, @scope.instance_variable_get(name))
    end
  end

  @ivars.each do |name, value|
    instance_variable_set(name, value)
  end
  
  instance_exec(*args, &block)
end

#xsend(name, *args, &block) ⇒ Object

Send a message, that completely bypasses the locals and the scope and is added directly to #messages.



73
74
75
# File 'lib/exec_env/env.rb', line 73

def xsend (name, *args, &block)
  @messages << [name, args, block]
end