Sha256: 6659516f3e73d3d887c1d4fd3d45ab0485b4cf3c39f359b9cfa273a36701f392

Contents?: true

Size: 1.75 KB

Versions: 12

Compression:

Stored size: 1.75 KB

Contents

class Code
  class Node
    class If < Node
      IF_KEYWORD = "if"
      UNLESS_KEYWORD = "unless"

      class Else
        def initialize(else_parsed)
          if else_parsed.key?(:operator)
            @operator = else_parsed.fetch(:operator)
            @statement =
              ::Code::Node::Statement.new(else_parsed.fetch(:statement))
          end

          @body = ::Code::Node::Code.new(else_parsed.fetch(:body))
        end

        attr_reader :operator, :body, :statement
      end

      def initialize(if_parsed)
        @if_operator = if_parsed.fetch(:if_operator)
        @if_statement =
          ::Code::Node::Statement.new(if_parsed.fetch(:if_statement))
        @if_body = ::Code::Node::Code.new(if_parsed.fetch(:if_body))
        @elses = if_parsed.fetch(:elses, [])
        @elses.map! { |else_parsed| ::Code::Node::If::Else.new(else_parsed) }
      end

      def evaluate(**args)
        if_object = @if_statement.evaluate(**args)

        if @if_operator == IF_KEYWORD && if_object.truthy?
          @if_body.evaluate(**args)
        elsif @if_operator == UNLESS_KEYWORD && if_object.falsy?
          @if_body.evaluate(**args)
        else
          @elses.each do |else_node|
            if else_node.operator == IF_KEYWORD
              else_object = else_node.statement.evaluate(**args)
              return else_node.body.evaluate(**args) if else_object.truthy?
            elsif else_node.operator == UNLESS_KEYWORD
              else_object = else_node.statement.evaluate(**args)
              return else_node.body.evaluate(**args) if else_object.falsy?
            elsif else_node.operator.nil?
              return else_node.body.evaluate(**args)
            end
          end

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

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
template-ruby-0.4.0 lib/code/node/if.rb
code-ruby-0.4.0 lib/code/node/if.rb
template-ruby-0.3.1 lib/code/node/if.rb
code-ruby-0.3.1 lib/code/node/if.rb
template-ruby-0.3.0 lib/code/node/if.rb
code-ruby-0.3.0 lib/code/node/if.rb
code-ruby-0.2.4 lib/code/node/if.rb
template-ruby-0.2.4 lib/code/node/if.rb
template-ruby-0.2.3 lib/code/node/if.rb
template-ruby-0.2.2 lib/code/node/if.rb
template-ruby-0.2.1 lib/code/node/if.rb
template-ruby-0.2.0 lib/code/node/if.rb