Tuesday, January 29, 2013

Generate XML in Rails and Ruby

If you're lucky enough to have a Rails console, you can use the to_xml to return a string containing an XML representation of its receiver:


{"fname" => "foo", "lname" => "bar"}.to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <hash>
#   <fname type="string">foo</fname>
#   <lname type="string">bar</lname>
# </hash>

If you don't have the luxury of the Rails framework, then checkout the XML Builder gem.


Install Builder

$ gem install builder

Alternatively, you can put it in your Gemfile.

Open an irb Console


$ irb



irb(main):001:0> require 'active_support/builder' unless defined?(Builder)
=> true

Use Builder's XmlMarkup  functionality


builder = Builder::XmlMarkup.new(:target=>STDOUT, :indent=>2)
builder.person { |b| b.fname("foo"); b.lname("bar") }


To generate XML


<person>
  <fname>foo</fname>
  <lname>bar</lname>
</person>

If you are interested in how the Builder code leverages Ruby's dynamic language features to make this magic happen, take a look at the humbug article below.


References

http://apidock.com/rails/v3.1.0/Hash/to_xml
http://www.humbug.in/docs/ruby-best-practices/I_sect13_d1e2654.html


Sponsor Ads


5 comments:

  1. readings were really very good. I will bookmark this blog so that I could often visit this blog often to read the latest article from your blog. I wait for your arrival at our website ...

    thanks, ...



    By : ios development jakarta | firzil.co.id

    ReplyDelete
  2. awesome post presented by you..your writing style is fabulous and keep update with your blogs Ruby on Rails Online Course Hyderabad

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete