Hi! I'm Nathan Hoad

Intro to iPhone-optimising your Rails site

Creating an iPhone optimised version of your web site is fairly straight forward. The setup process is simple and then from there you can be as thorough as you want to be.

To start with open config/initializers/mime_types.rb and make sure this is there:

Mime::Type.register_alias "text/html", :iphone

Then, in your application controller, add one of these:

before_filter :format_for_iphone

def format_for_iphone
  # There are 2 ways you can do this, a subdomain or automatically
  # NOTE: You don't really need both

  # option 1: subdomain
  if request.subdomains.first == "iphone" || params[:format] == "iphone"
    request.format = :iphone

  # option 2: automatic
  if request.env["HTTP_USER_AGENT"] and request.env["HTTP_USER_AGENT"][/(Mobile\/.+Safari)/]
    request.format = :iphone

ERB picks up on the mime type of the request so just create views with .iphone.erb instead of .html.erb. For example, create a view called index.iphone.erb for the index action of a controller.

You will also need an application layout for the iPhone pages. Create app/views/layouts/application.iphone.erb with some html for your layout. Make sure to include something like this in the <head> of the document:

<meta id="viewport" name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1; user-scalable=0;" />

This sets up the zoom/scaling configuration for your site. The device-width is 320 when in portrait orientation and 480 when in landscape orientation. Setting the width to device-width lets the phone resize the viewport whenever the user changes their orientation. Setting maxium-scale to 1 and user-scalable to 0 means the user won't be able to zoom in on your pages. For most web apps this would be desirable because the user interface should be designed to always be the right size anyhow.

One problem (for me, anyway) that I came across was that my full site has a content width of 480px but the default portrait width for the iPhone is 320px. This wouldn't have been too much of an issue but some of my uploaded images were assuming a width of at least 450px. To get around that problem I figured that all I needed to do was set the default zoom to be something like 0.666. That would mean that I could fake a portrait width of about 480px. The only downside to doing it the lazy way is that any other images (eg. emoticons ) are now about 1/3 smaller than they should be.

Once you have the layout stuff down you can just keep adding iPhone versions of any Views that you want to be mobile-optimised.

Something else you might want to add is a Springboard/Home Screen icon.

If I just made your day a little better then thank me with a coffee or maybe a a pizza