Class: Simulator::VariableContext

Inherits:
Object
  • Object
show all
Defined in:
lib/simulator/variable_context.rb

Instance Method Summary collapse

Constructor Details

#initializeVariableContext

Returns a new instance of VariableContext.



3
4
5
# File 'lib/simulator/variable_context.rb', line 3

def initialize
  @variables_hash = {}
end

Instance Method Details

#add(var_hash) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/simulator/variable_context.rb', line 7

def add(var_hash)
  vars = var_hash.collect do |k, v|
    Variable.new k
  end
  add_variables *vars
  set var_hash
end

#add_variables(*vars) ⇒ Object

add variables. doesn’t check for uniqueness, does not overwrite existing



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/simulator/variable_context.rb', line 16

def add_variables(*vars)
  # create bound variables for each variable
  bound_vars = vars.collect do |v|
    BoundVariable.new v, self
  end

  # add all the bound variables to the variables hash
  keys = vars.collect(&:name)
  append_hash = Hash[ keys.zip(bound_vars) ]
  @variables_hash.merge!(append_hash) do |key, oldval, newval|
    oldval # the first bound variable
  end
end

#cloneObject



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/simulator/variable_context.rb', line 52

def clone
  copy = VariableContext.new
  copy.add_variables *unbound_variables

  # create a value hash of variable names and values
  value_hash = variables.inject({}) do |memo, v|
    memo[v.name] = v.value
    memo
  end
  copy.set value_hash
  copy
end

#get(var_name) ⇒ Object



40
41
42
# File 'lib/simulator/variable_context.rb', line 40

def get(var_name)
  @variables_hash[var_name]
end

#set(var_hash) ⇒ Object

Use to set the value for a variety of variables



31
32
33
34
35
36
37
38
# File 'lib/simulator/variable_context.rb', line 31

def set(var_hash)
  var_hash.each do |variable_name, value|
    throw :MissingVariable unless @variables_hash.has_key? variable_name

    bv = @variables_hash[variable_name]
    bv.value = value
  end
end

#unbound_variablesObject



48
49
50
# File 'lib/simulator/variable_context.rb', line 48

def unbound_variables
  variables.collect(&:variable)
end

#variablesObject



44
45
46
# File 'lib/simulator/variable_context.rb', line 44

def variables
  @variables_hash.values
end