diff --git a/lib/oga/ruby/generator.rb b/lib/oga/ruby/generator.rb index f2563db..2f80cf0 100644 --- a/lib/oga/ruby/generator.rb +++ b/lib/oga/ruby/generator.rb @@ -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 ## diff --git a/lib/oga/ruby/node.rb b/lib/oga/ruby/node.rb index 36f52d3..72c8972 100644 --- a/lib/oga/ruby/node.rb +++ b/lib/oga/ruby/node.rb @@ -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. # diff --git a/spec/oga/ruby/generator_spec.rb b/spec/oga/ruby/generator_spec.rb index 973b100..73d3b86 100644 --- a/spec/oga/ruby/generator_spec.rb +++ b/spec/oga/ruby/generator_spec.rb @@ -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 diff --git a/spec/oga/ruby/node_spec.rb b/spec/oga/ruby/node_spec.rb index 744f3b7..a364298 100644 --- a/spec/oga/ruby/node_spec.rb +++ b/spec/oga/ruby/node_spec.rb @@ -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})