class Jsrb::CondChain

Public Class Methods

new(context, as_expr) click to toggle source
# File lib/jsrb/cond_chain.rb, line 5
def initialize(context, as_expr)
  @context = context
  @as_expr = as_expr
  @stack = []
end

Public Instance Methods

else(&block) click to toggle source
# File lib/jsrb/cond_chain.rb, line 16
def else(&block)
  finalize(block)
end
elsif(expr, &block) click to toggle source
# File lib/jsrb/cond_chain.rb, line 11
def elsif(expr, &block)
  add_case(expr, block)
  self
end
end() click to toggle source
# File lib/jsrb/cond_chain.rb, line 20
def end
  finalize(nil)
end

Private Instance Methods

add_case(expr, block) click to toggle source
# File lib/jsrb/cond_chain.rb, line 26
def add_case(expr, block)
  @stack << [@context.ruby_to_js_ast(expr), block]
end
create_proc(block) click to toggle source
# File lib/jsrb/cond_chain.rb, line 46
def create_proc(block)
  lambda do
    final_alternate_stmt = block && @context.new_block do
      @context.push(
        type: 'ReturnStatement',
        argument: {
          type: 'CallExpression',
          callee: @context.ruby_to_js_ast(block),
          arguments: []
        }
      )
    end
    if_stmt = @stack.reverse.reduce(final_alternate_stmt) do |alternate_stmt, cond_block|
      condition_expr, cond_block = cond_block
      consequent_stmt = @context.new_block do
        @context.push(
          type: 'ReturnStatement',
          argument: {
            type: 'CallExpression',
            callee: @context.ruby_to_js_ast(cond_block),
            arguments: []
          }
        )
      end
      stmt_ast = {
        type: 'IfStatement',
        test: condition_expr,
        consequent: consequent_stmt
      }
      stmt_ast[:alternate] = alternate_stmt if alternate_stmt
      stmt_ast
    end
    @context.push(if_stmt)
  end
end
finalize(block) click to toggle source
# File lib/jsrb/cond_chain.rb, line 30
def finalize(block)
  if_value = @context.new_expression(
    type: 'CallExpression',
    callee: @context.ruby_to_js_ast(create_proc(block)),
    arguments: []
  )
  if @as_expr
    if_value
  else
    @context.push(
      type: 'ExpressionStatement',
      expression: if_value.object
    )
  end
end