Rendering different views for a given action

Gleb Mazovetskiy wrote:

Hi, everyone, this is my first post here!

I have a "HomeController" that has an "index" method.

I have 4 views for this method:
- index.html.erb
- index.mobile_lofi.erb
- index.mobile_hifi.erb
- index.iphone.erb

I also have the following mimetypes defined:
Mime::Type.register_alias "text/html", :mobile_lofi
Mime::Type.register_alias "text/html", :mobile_hifi
Mime::Type.register_alias "text/html", :iphone

Now, the content (instance variables) these views need is almost the
same among them.

I have a method "device_type?" that returns one of the [:html,
:mobile_lofi, :mobile_hifi, :iphone] based on the User-Agent string.

How do I render the view based on the result of the "device_type?"
I am using Rails 2.3.3.

Thank you,

Gleb, I am not sure, but i would think along these line

  def index
    format = device_type?
    respond_to do |format|
      format.mobile_lofi { render blah}
      format.iphone { render :action => blah }


Craigslist Clone in Rails

Close, but I think you need to set request.format, and I'd probably do
that in a before filter.

  class HomeController < ApplicationController
      before_filter :set_device_mime_type

     def set_device_mime_type
         request.format = device_type?

     def index
         respond_to do |format|
             #what you said

I'd also strongly suggest renaming that device_type? method to
something like device_mime_type since the question mark indicates that
it should be a predicate method.

It might also be a good idea to refactor this a bit so that you only
change the format of the request if it is coming from one of the
special devices, and leave it to what the client sent otherwise.

Thanks a lot, Rick!