From d8fbaf75d88404f9a9cb9ed18289c674b459f822 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Fri, 17 Jul 2015 00:56:02 +0200 Subject: [PATCH] Ruby generator support for while loops --- lib/oga/ruby/generator.rb | 19 +++++++++++++++++++ lib/oga/ruby/node.rb | 12 ++++++++++++ spec/oga/ruby/generator_spec.rb | 14 ++++++++++++++ spec/oga/ruby/node_spec.rb | 13 ++++++++++++- 4 files changed, 57 insertions(+), 1 deletion(-) diff --git a/lib/oga/ruby/generator.rb b/lib/oga/ruby/generator.rb index 6f3f5f9..e058f49 100644 --- a/lib/oga/ruby/generator.rb +++ b/lib/oga/ruby/generator.rb @@ -117,6 +117,25 @@ 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. # diff --git a/lib/oga/ruby/node.rb b/lib/oga/ruby/node.rb index 72c8972..da5c1d9 100644 --- a/lib/oga/ruby/node.rb +++ b/lib/oga/ruby/node.rb @@ -114,6 +114,18 @@ module Oga Node.new(:if, [self, yield]) 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. # diff --git a/spec/oga/ruby/generator_spec.rb b/spec/oga/ruby/generator_spec.rb index b7b94b3..60c2540 100644 --- a/spec/oga/ruby/generator_spec.rb +++ b/spec/oga/ruby/generator_spec.rb @@ -87,6 +87,20 @@ 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 'without arguments' do it 'returns a String' do diff --git a/spec/oga/ruby/node_spec.rb b/spec/oga/ruby/node_spec.rb index a364298..9d04f0f 100644 --- a/spec/oga/ruby/node_spec.rb +++ b/spec/oga/ruby/node_spec.rb @@ -89,7 +89,7 @@ describe Oga::Ruby::Node do end 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}) body = described_class.new(:lit, %w{10}) statement = condition.if_true { body } @@ -99,6 +99,17 @@ describe Oga::Ruby::Node do 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 it 'returns an if-statement with an else clause' do condition = described_class.new(:lit, %w{number})