Class: Code::Node::If

Inherits:
Code::Node show all
Defined in:
lib/code/node/if.rb

Defined Under Namespace

Classes: Else

Constant Summary collapse

IF_KEYWORD =
"if"
UNLESS_KEYWORD =
"unless"
ELSIF_KEYWORD =
"elsif"
ELSUNLESS_KEYWORD =
"elsunless"
ELSE_KEYWORD =
"else"

Instance Method Summary collapse

Methods inherited from Code::Node

#resolve

Constructor Details

#initialize(parsed) ⇒ If

Returns a new instance of If.



27
28
29
30
31
32
33
34
35
36
# File 'lib/code/node/if.rb', line 27

def initialize(parsed)
  return if parsed.blank?

  @first_operator = parsed.delete(:first_operator).presence
  @first_statement =
    Node::Statement.new(parsed.delete(:first_statement).presence)
  @first_body = Node::Code.new(parsed.delete(:first_body).presence)
  @elses = parsed.delete(:elses).presence || []
  @elses.map! { |elses| Node::If::Else.new(elses) }
end

Instance Method Details

#evaluate(**args) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/code/node/if.rb', line 38

def evaluate(**args)
  if (
       @first_operator == IF_KEYWORD &&
         @first_statement.evaluate(**args).truthy?
     ) ||
       (
         @first_operator == UNLESS_KEYWORD &&
           @first_statement.evaluate(**args).falsy?
       )
    @first_body.evaluate(**args)
  else
    (@elses || []).each do |elses|
      if (
           elses.operator == ELSIF_KEYWORD &&
             elses.statement.evaluate(**args).truthy?
         ) ||
           (
             elses.operator == ELSUNLESS_KEYWORD &&
               elses.statement.evaluate(**args).falsy?
           ) ||
           (
             elses.operator == IF_KEYWORD &&
               elses.statement.evaluate(**args).truthy?
           ) ||
           (
             elses.operator == UNLESS_KEYWORD &&
               elses.statement.evaluate(**args).falsy?
           ) || (elses.operator == ELSE_KEYWORD)
        return elses.body.evaluate(**args)
      end
    end

    ::Code::Object::Nothing.new
  end
end