Class: Dentaku::AST::Case

Inherits:
Node
  • Object
show all
Defined in:
lib/dentaku/ast/case.rb

Overview

Examples of using in a formula:

CASE x WHEN 1 THEN 2 WHEN 3 THEN 4 ELSE END

CASE fruit
WHEN 'apple'
  THEN 1 * quantity
WHEN 'banana'
  THEN 2 * quantity
ELSE
  3 * quantity
END

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

arity, #name, precedence, resolve_class, #type

Constructor Details

#initialize(*nodes) ⇒ Case

Returns a new instance of Case.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dentaku/ast/case.rb', line 33

def initialize(*nodes)
  @switch = nodes.shift

  unless @switch.is_a?(AST::CaseSwitchVariable)
    raise ParseError.for(:node_invalid), 'Case missing switch variable'
  end

  @conditions = nodes

  @else = nil
  @else = @conditions.pop if @conditions.last.is_a?(AST::CaseElse)

  @conditions.each do |condition|
    unless condition.is_a?(AST::CaseConditional)
      raise ParseError.for(:node_invalid), "#{condition} is not a CaseConditional"
    end
  end
end

Instance Attribute Details

#conditionsObject (readonly)

Returns the value of attribute conditions.



23
24
25
# File 'lib/dentaku/ast/case.rb', line 23

def conditions
  @conditions
end

#elseObject (readonly)

Returns the value of attribute else.



23
24
25
# File 'lib/dentaku/ast/case.rb', line 23

def else
  @else
end

#switchObject (readonly)

Returns the value of attribute switch.



23
24
25
# File 'lib/dentaku/ast/case.rb', line 23

def switch
  @switch
end

Class Method Details

.max_param_countObject



29
30
31
# File 'lib/dentaku/ast/case.rb', line 29

def self.max_param_count
  Float::INFINITY
end

.min_param_countObject



25
26
27
# File 'lib/dentaku/ast/case.rb', line 25

def self.min_param_count
  2
end

Instance Method Details

#accept(visitor) ⇒ Object



74
75
76
# File 'lib/dentaku/ast/case.rb', line 74

def accept(visitor)
  visitor.visit_case(self)
end

#dependencies(context = {}) ⇒ Object



67
68
69
70
71
72
# File 'lib/dentaku/ast/case.rb', line 67

def dependencies(context = {})
  # TODO: should short-circuit
  switch_dependencies(context) +
  condition_dependencies(context) +
  else_dependencies(context)
end

#value(context = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/dentaku/ast/case.rb', line 52

def value(context = {})
  switch_value = @switch.value(context)
  @conditions.each do |condition|
    if condition.when.value(context) == switch_value
      return condition.then.value(context)
    end
  end

  if @else
    return @else.value(context)
  else
    raise ArgumentError.for(:invalid_value), "No block matched the switch value '#{switch_value}'"
  end
end