Where’s the Glue?

July 26, 2006

Perhaps I’m out of the loop on this one, but I’ve found an odd gap between edge Rails and the simply_restful plugin. Here’s what’s up:

The Controller


ShoesController < ApplicationController
  ...
  def show
    @shoe = Shoe.find @params[:id]
  end
  ...
end

The Views


app/shoes/show.rhtml
         /show.rxml
         /show.rjs

My Expectation

When I GET /shoes/1.xml I get the XML format via the show.rxml file, and when I GET /shoes/1.html I get the HTML format via the show.rhtml file — afterall, the format is specified in the request, and passed through as @params[:format].

Unfortunately, I don’t have deep knowledge of the internal Rails code (yet!), so I kludged together a quick workaround that automatically determines format-based views.

The Workaround


def render_formatted
  @params[:format] ||= "html"  # Default format
  # build the preferred template path
  template = "#{RAILS_ROOT}/app/views/#{@params[:controller]}/#{@params[:action]}.r#{@params[:format]}"
  if File.exist? template
    render :file => template
  else
    render :text => "'#{@params[:format]}' format not available for '#{@request.path}'", :status => 404
  end
end

In practice, #render_formatted would be called at the end of any given action to provide the appropriate response. Know a better way to do this? Any feedback would be appreciated, especially if I’m missing a vital link in the clue train …

Thanks!

3 Responses to “Where’s the Glue?”


  1. May responds_to is what you’re looking for?

    respond_to do |wants|
    wants.html
    wants.js
    wants.xml { render :xml => @shoe.to_xml }
    end

  2. Peat Says:

    Jonathan: respond_to is great for when I need to manually tweak the behavior, but I find it awkward if to specify the set of wants.xxxx for every action, especially when I’m already telling it what I want through @params[:format], and what’s available in the view directory for that controller.

    I’ll see if I can dig a bit deeper in the next week. Thanks for the suggestion!

  3. Jamie Hill Says:

    You could put the responds_to block in a before_filter that gets called for all actions and any that you don’t want it to affect set :except => [:action1, :action2, :etc]

    I’m also playing around with the Simply RESTful plugin. Although unrelated to your problem, you may find this handy: http://thelucid.com/articles/2006/07/26/simply-restful-the-missing-action


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: