Forum: Ruby xml parsing in blocks

Posted by Aashish Kiran (aashishkiran)
on 2013-03-18 13:15
Hi,
I was writing a small program as follows, But could not get expected
output.
Can anyone help.
--------------------------xml_document.rb-----------------------------
  class XmlDocument
  attr_accessor :format

  def initialize(format = nil)
    self.format = format
  end

  def method_missing(name, *args, &block)
    self.class.class_eval do
      define_method(name) do |*args, &block|
        temp = ''
        if args[0]
          args[0].each do |k, v|
            temp = temp + " #{k}='#{v}'"
          end
        end

        if block
          temp = "<#{name}#{temp}>" + block.call + "</#{name}>"
        else
          temp = "<#{name}" + temp + "/>"
        end
        temp
      end
    end


    send(name, *args, &block)


  end
end
-----------------------end of xml_document.rb---------------------------
o/p : <hello><goodbye><come_back><ok_fine
be='that_way'/></come_back></goodbye></hello>
expected o/p : <hello>\n  <goodbye>\n    <come_back>\n      <ok_fine
be='that_way'/>\n    </come_back>\n  </goodbye>\n</hello>\n

@xml = XmlDocument.new(true)
    @xml.hello do
      @xml.goodbye do
        @xml.come_back do
          @xml.ok_fine(:be => "that_way")
        end
      end
    end.should ==
    "<hello>\n" +
    "  <goodbye>\n" +
    "    <come_back>\n" +
    "      <ok_fine be='that_way'/>\n" +
    "    </come_back>\n" +
    "  </goodbye>\n" +
    "</hello>\n"
  end
Posted by Robert Klemme (robert_k78)
on 2013-03-18 13:46
(Received via mailing list)
On Mon, Mar 18, 2013 at 1:15 PM, Aashish Kiran <lists@ruby-forum.com> 
wrote:
> Hi,
> I was writing a small program as follows, But could not get expected
> output.
> Can anyone help.

Why don't you use Builder?

Cheers

robert
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.