开发者

newbie xml builder question for a rails 3 app

I've never used xml builder in my rails 3 app, but need to start开发者_如何学C.

one of our controller methods is invoked by a remote system, and it returns only xml.

in our foo controller we have

  def return_some_data
    @thename = "JOHN DOE" 
      respond_to do |format|
        format.xml
      end
  end

in our views/foo/return_some_data.xml.erb we have

<Response>
  <Name>The name is <%= @thename %></Name>
</Response>

I would like to use xml builder instead of manually creating the xml and using erb to handle variable insertion.

I think the equivalent builder file would look like this?

xml.Response{
  xml.Name(The name is @thename)
}

Also what would I rename the file return_some_data and which folder would I put it in? Also, do I need a 'require' or 'include' to start using xml builder, or is it a ruby built-in?


the view should have extension .builder eg. views/foo/return_some_data.builder

by naming it .builder, rails automatically creates you an instance of XmlMarkup also your .builder templates are pure ruby no erb necessary

xml.instruct!
xml.Response do
  xml.Name @name
end


I have used xml builder. Following code snippet covers some tricky xml building.

In you controller,

require 'builder'

def show_xml
  get_xml_data
  respond_to do |format|
    format.html # show.html.erb
    format.xml { render :xml => @xml }
  end
end

def get_xml_data
  xml = Builder::XmlMarkup.new#(:target=>$stdout, :indent=>2)
  xml.instruct! :xml, :version => "1.0", :encoding => "US-ASCII"
  xml.declare! :DOCTYPE, :html, :PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN",  
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
  favorites = {
    'candy' => 'Neccos', 'novel' => 'Empire of the Sun', 'holiday' => 'Easter'
  }

  @xml = xml.favorites do
    favorites.each do | name, choice |
     xml.favorite( choice, :item => name )
    end
  end
end

In this case you dont need to create partials. It comes with core libraries so no need to install just require it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜