Choosing Layouts at Runtime in Ruby on Rails - iPhone Safari x Firefox or IE on a PC

I wanted to set a different layout in my application depending on a decision of a special situation. For example, if the client system is a browser on an iPhone I'd like to show a different layout than a Firefox running in a PC.

I found inspiration on the official RoR documentation, specifically on the page about the rendering mechanism. Here is the code I wrote to display a specific layout if the client browser is a Safari running in a iPhone or iPod touch.

All you have to do is add some methods to your ApplicationController and have another layout file in your /views/layouts folder. Check the commented code below:

class ApplicationController < ActionController::Base
  # this is the call to the private method that returns which
  # layout should be used; the "layout" method call allows
  # the system to decide at runtime which is the correct layout
  # file to choose
  layout :iphone_layout

  # this method uses a regular expression to match the text
  # that would describe the browser used by the client
  def is_iphone_request?
    request.user_agent =~ /(Mobile\/.+Safari)/
  end

  private

  # this method will choose the name of the layout file to be used
  # these files should exist in the views/layouts folder
  def iphone_layout
    is_iphone_request? ? "iphone" : "application"
  end
end

Comments

Maybe a better approach?

I found this article from IBM which might be a more robust/complete (although more complex) solution to the one I mentioned above.

Developing iPhone applications using Ruby on Rails and Eclipse, Part 1: Serving content for iPhones: http://www.ibm.com/developerworks/opensource/library/os-eclipse-iphoneru...

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options