George
George

Reputation: 4473

Rails to_xml, use xml attributes instead of child nodes

I've been playing around with rail's to_xml, trying to create a really simple rest interface for a project i'm working on.

So far, i've come up with

cards = Card.all(:conditions => {:racedate => Date.today.to_s})
render :xml => cards.to_xml(:include => {:races => { :only => [:id, :number, :race_time, :name] } }, :skip_types => true, :root => "cards")    

in my controller.

This produces some xml.

    <card>
     <country-code>USA</country-code>
     <id>55</id>
     <name>Vernon Downs</name>
     <races>
      <race>
        <id>355</id>
        <name/>
        <number>1</number>
        <race-time/>
      </race>
    </races>
   </card>

What i'd really like is to use xml attributes rather than child nodes, so it would be

<card country-code="USA" id=55 name="Vernon Downs"/> etc.

I've poured over the to_xml api docs but can't seem to find any way of doing this? Do i need to create an xml template and render that way?

Thanks

Upvotes: 3

Views: 1809

Answers (2)

freemanoid
freemanoid

Reputation: 14770

Here is an example of method that uses attributes if it possible:

def self.format_xml(root, hash, builder = Builder::XmlMarkup.new)
    # separate apples from oranges
    enums = {}
    vals = {}
    hash.each do |k, v|
      if Enumerable === v
        enums[k] = v
      elsif v.respond_to? :to_s
        vals[k] = v
      else
        fail InvalidValueType, {k => v}
      end
    end
    # build not enumerable values
    builder.tag!(root, vals) do
      # recursively call for values from enums
      enums.each do |k, v|
        self.format_xml(k, v, builder)
      end
    end
  end

Upvotes: 0

George
George

Reputation: 4473

I couldn't figure out a nicer way to do this, so i ended up with a view to render the xml as i wanted.

Code for anyone that's interested..

Controller:

    @cards = Card.all(:select => "id,name,country_code,racedate,track_code", :conditions => {:racedate => Date.today.to_s})

   response.headers['Content-type'] = 'text/xml; charset=utf-8'
   render :layout => false

View :

    <?xml version="1.0" encoding="UTF-8"?>
<cards>
<% @cards.each do |card| -%>
    <card card-name="<%= card.name %>" id="<%= card.id %>" country-code="<%= card.country_code %>" card-date="<%= card.racedate %>" track-code="<%= card.track_code %>">
        <races>
    <% card.races.each do |race| -%>
        <race name="<%= race.name %>" id="<%= race.id %>" tote-race-number="<%= race.number %>" post-time="<%= race.race_time %>"></race>
    <% end -%>
    </races>
    </card>
<% end -%>
</cards>

Upvotes: 1

Related Questions