Class: Romanesco::ExpressionTree

Inherits:
Object
  • Object
show all
Defined in:
lib/romanesco/expression_tree.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression) ⇒ ExpressionTree

Returns a new instance of ExpressionTree.



8
9
10
11
# File 'lib/romanesco/expression_tree.rb', line 8

def initialize(expression)
  @original_expression = expression
  @required_variables = []
end

Instance Attribute Details

#last_operandObject

Returns the value of attribute last_operand.



5
6
7
# File 'lib/romanesco/expression_tree.rb', line 5

def last_operand
  @last_operand
end

#last_operatorObject

Returns the value of attribute last_operator.



5
6
7
# File 'lib/romanesco/expression_tree.rb', line 5

def last_operator
  @last_operator
end

#original_expressionObject

Returns the value of attribute original_expression.



5
6
7
# File 'lib/romanesco/expression_tree.rb', line 5

def original_expression
  @original_expression
end

#required_variablesObject (readonly)

Returns the value of attribute required_variables.



6
7
8
# File 'lib/romanesco/expression_tree.rb', line 6

def required_variables
  @required_variables
end

Instance Method Details

#add(element) ⇒ Object



13
14
15
16
17
18
# File 'lib/romanesco/expression_tree.rb', line 13

def add(element)
  element.connect(@last_operator, @last_operand)
  @last_operand = element if element.is_a? Operand
  @last_operator = element if element.is_a? Operator
  @required_variables << element.name.to_sym if element.is_a? VariableOperand
end

#close_parenthesisObject



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/romanesco/expression_tree.rb', line 20

def close_parenthesis
  if last_operator.is_a? ParenthesesOperator
    current_node = @last_operator
  else
    current_node = @last_operand
    until current_node.is_a? ParenthesesOperator || current_node.parent.nil?
      current_node = current_node.parent
    end
  end

  current_node.precedence = 0
  @last_operand = @last_operator = current_node
end

#evaluate(options = {}, default_value = nil) ⇒ Object

Raises:



34
35
36
37
38
39
40
# File 'lib/romanesco/expression_tree.rb', line 34

def evaluate(options={}, default_value=nil)
  start = starting_point
  check_for_loops(start, options)
  missing_variables, new_options = check_for_missing_variables(start, options, [], default_value)
  raise MissingVariables.new("Missing variables: #{missing_variables.join', '}", missing_variables) unless missing_variables.empty?
  start.evaluate(new_options)
end

#starting_pointObject



46
47
48
49
50
51
52
53
# File 'lib/romanesco/expression_tree.rb', line 46

def starting_point
  return @starting_point if @starting_point
  current_node = @last_operand
  until current_node.parent.nil?
    current_node = current_node.parent
  end
  @starting_point = current_node
end

#to_sObject



42
43
44
# File 'lib/romanesco/expression_tree.rb', line 42

def to_s
  starting_point.to_s
end