Ruby generator support for while loops

This commit is contained in:
Yorick Peterse 2015-07-17 00:56:02 +02:00
parent 9925b2a9c9
commit d8fbaf75d8
4 changed files with 57 additions and 1 deletions

View File

@ -117,6 +117,25 @@ end
end end
end end
##
# Processes a while statement node.
#
# @param [Oga::Ruby::Node] ast
# @return [String]
#
def on_while(ast)
cond, body = *ast
cond_str = process(cond)
body_str = process(body)
<<-EOF
while #{cond_str}
#{body_str}
end
EOF
end
## ##
# Processes a method call node. # Processes a method call node.
# #

View File

@ -114,6 +114,18 @@ module Oga
Node.new(:if, [self, yield]) Node.new(:if, [self, yield])
end end
##
# Wraps the current node in a `while` statement.
#
# The body of this statement is set to the return value of the supplied
# block.
#
# @return [Oga::Ruby::Node]
#
def while_true
Node.new(:while, [self, yield])
end
## ##
# Adds an "else" statement to the current node. # Adds an "else" statement to the current node.
# #

View File

@ -87,6 +87,20 @@ end
end end
end end
describe '#on_while' do
it 'returns a String' do
statement = Oga::Ruby::Node.new(:lit, %w{foo}).while_true do
Oga::Ruby::Node.new(:lit, %w{bar})
end
@generator.on_while(statement).should == <<-EOF
while foo
bar
end
EOF
end
end
describe '#on_send' do describe '#on_send' do
describe 'without arguments' do describe 'without arguments' do
it 'returns a String' do it 'returns a String' do

View File

@ -89,7 +89,7 @@ describe Oga::Ruby::Node do
end end
describe '#if_true' do describe '#if_true' do
it 'returns an if-statement Node' do it 'returns an if statement Node' do
condition = described_class.new(:lit, %w{number}) condition = described_class.new(:lit, %w{number})
body = described_class.new(:lit, %w{10}) body = described_class.new(:lit, %w{10})
statement = condition.if_true { body } statement = condition.if_true { body }
@ -99,6 +99,17 @@ describe Oga::Ruby::Node do
end end
end end
describe '#while_true' do
it 'returns a while statement Node' do
condition = described_class.new(:lit, %w{number})
body = described_class.new(:lit, %w{10})
statement = condition.while_true { body }
statement.type.should == :while
statement.to_a.should == [condition, body]
end
end
describe '#else' do describe '#else' do
it 'returns an if-statement with an else clause' do it 'returns an if-statement with an else clause' do
condition = described_class.new(:lit, %w{number}) condition = described_class.new(:lit, %w{number})