XML Builder Partials in Rails

The past few days I've been creating an API with Rails and found that writing xml Builder files is slightly different then writing the usual erb in views.  The biggest problem was keeping things DRY and using partials, it just doesn't work the same way.  The following attempt to render does nothing in the xml.builder file:

render :partial => 'somepartial'

The reason is because the partial will receive a new xml Builder object rather than using the one already setup.  You can do a few tricks such as passing in the xml builder object in as a local variable, but I found out that the cleanest way to do it is:

xml << render :partial => 'somepartial'

Hope that helps people looking to make partials with the XML Builder in Rails

Posted
 

Create a simple API with Ruby on Rails

Here are the few easy steps to creating a simple API in a Ruby on Rails project.

  • Start a new rails app with the restful_authentication plugin by technoweenie: http://github.com/technoweenie/restful-authentication/
  • The restful_authentication plugin allows for user accounts, but doesn't have any API authentication built in.  If you want to make publicly available API keys for your users, you'll need to put this in so you can track API usage and deter any unauthorized use.  So assuming you have restful_authentication all setup with defaults, follow this tutorial for setting up API authentication: http://www.compulsivoco.com/2009/05/rails-api-authentication-using-restful-au...
  • Once you have the above api authentication applied, make sure all the actions that you want protected by the API authentication by adding a before filter:

before_filter :login_required, :only => [...array of actions to be protected...]

  • To render out xml for a certain object, you can simply use a respond_to when you're ready to render xml in the controller.

respond_to do |format|
  format.xml { render :xml => @some_object }
end

  • The above assumes you have an object that you want to return, and will dump the columns as needed.  If you want a prettier or custom return xml, I would recommend using the built in Builder that allows you to specify exactly what xml you want by creating a new view file called action_name.xml.builder and changing the respond_to line to the following:

respond_to do |format|
  format.xml
end

  • In your action_name.xml.builder, use the xml builder syntax to create your own xml file.  Here's a quick example:

xml.instruct!
xml.droplets do
  @droplets.each do |droplet|
    xml.droplet do
      xml.id droplet.id
      xml.name droplet.name
      xml.created_at droplet.created_at
    end
  end
end

  • You should test all of this using curl

http://localhost:3000/controller/action/param.xml?api_key=SOME_API_KEY

 

Posted