Support for generating "else" statements

This commit is contained in:
Yorick Peterse 2015-07-08 01:56:38 +02:00
parent ac6c0d806e
commit 2c1b4e7cbc
4 changed files with 56 additions and 3 deletions

View File

@ -93,16 +93,28 @@ module Oga
# @return [String]
#
def on_if(ast)
cond, body = *ast
cond, body, else_body = *ast
cond_str = process(cond)
body_str = process(body)
<<-EOF
if else_body
else_str = process(else_body)
<<-EOF
if #{cond_str}
#{body_str}
else
#{else_str}
end
EOF
else
<<-EOF
if #{cond_str}
#{body_str}
end
EOF
EOF
end
end
##

View File

@ -114,6 +114,17 @@ module Oga
Node.new(:if, [self, yield])
end
##
# Adds an "else" statement to the current node.
#
# This method assumes it's being called only on "if" nodes.
#
# @return [Oga::Ruby::Node]
#
def else
Node.new(:if, @children + [yield])
end
##
# Chains two nodes together.
#

View File

@ -67,6 +67,24 @@ if foo
end
EOF
end
describe 'when using an else clause' do
it 'returns a String' do
foo = Oga::Ruby::Node.new(:lit, %w{foo})
bar = Oga::Ruby::Node.new(:lit, %w{bar})
baz = Oga::Ruby::Node.new(:lit, %w{baz})
statement = foo.if_true { bar }.else { baz }
@generator.on_if(statement).should == <<-EOF
if foo
bar
else
baz
end
EOF
end
end
end
describe '#on_send' do

View File

@ -99,6 +99,18 @@ describe Oga::Ruby::Node do
end
end
describe '#else' do
it 'returns an if-statement with an else clause' do
condition = described_class.new(:lit, %w{number})
body = described_class.new(:lit, %w{10})
or_else = described_class.new(:lit, %w{20})
statement = condition.if_true { body }.else { or_else }
statement.type.should == :if
statement.to_a.should == [condition, body, or_else]
end
end
describe '#followed_by' do
it 'returns a Node chaining two nodes together' do
node1 = described_class.new(:lit, %w{A})