开发者

Ruby on Rails XML

I'm开发者_如何学C looking to create a Rails application which generates XML instead of HTML. How do I do this?


You have three options.

Option 1 is to explicitly render auto-generated XML.

render :xml => @object

which will call @object.to_xml for you. You can tweak the output with options:

render :xml => @object.to_xml(:except => [:private1, :private2], :include => [:associated_class])

This is very quick and easy. It will work pretty well if you don't need tight control of the output. The XML representation is being controlled in the controller instead of the view, which is somewhat messy, but not too bad as long as you're not getting fancy.

Option 2 is to create templates named .xml.erb instead of the normal .html.erb. These are just XML files with normal ERB markup in them. If the request comes in for an URL with .xml on the end of it, the default behaviour (using normal scaffolding in the controller) is to display those templates instead of the HTML ones). Frequently scaffolds have a block like:

respond_to do |format|
  format.html # show.html.erb
  format.xml { render :xml => @object.to_xml }
end

In this case (assuming you want to allow HTML as well) you'd want to remove the {} block on the format.xml line so it falls back to the default template.

Option 3 is to write your own object -> XML mapping, using something like Builder (which is very very slick and is included with Rails). Suddenly your model is worrying about its views.

I'd suggest doing option 1 until you start running into trouble (sometimes a seemingly benign change will cause the XML output to change - perhaps reordering tags) and then switch to option 2. Having those XML files there makes it very very clear exactly what's being displayed, much like having HTML view files. Option 3 works, but you're mixing logic (the rest of your model) with presentation.


You can either use the Builder library for Ruby, or use ActiveRecord's XML serialization functionality.


Here you have:

http://www.xml.com/pub/a/2007/01/17/making-xml-in-a-rails-app-xml-builder.html

Hope it serves!


You write XML instead of HTML. Rails doesn't particularly care what it serves.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜