Support for generating "else" statements
This commit is contained in:
parent
ac6c0d806e
commit
2c1b4e7cbc
|
@ -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
|
||||
|
||||
##
|
||||
|
|
|
@ -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.
|
||||
#
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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})
|
||||
|
|
Loading…
Reference in New Issue