Where’s the Glue?
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!
By Jonathan Conway
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
By Peat
Jonathan:
respond_tois great for when I need to manually tweak the behavior, but I find it awkward if to specify the set ofwants.xxxxfor 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!
By Jamie Hill
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