For a primer on Ruby on Rails, take a look at the Related Resources connected to this article.
|What You Need|
|An iPhone, or iPhony (iPhone browser emulator), a simple Ruby project over which you have control, and boundless imagination.|
Recognizing the iPhone
There are several different ways to detect if one of your visitors is hitting your page from an iPhone. Most of them rely on temporary "hacks" for assuming that safari is the only browser that will correctly accept "max-device-width" parameters. Since Ruby is all about simplicity, you should strive for a solution that is low in maintainability. Here’s the simple Ruby way of detecting the existence of the iPhone:
<%= if request.user_agent.include?("iPhone") then
render :partial => 'foriphoneonly'
Let's go over this code step-by-step:
- The code looks for "iPhone" within the user agent string. The full user iPhone UAString looks something like this:
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+
(KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3"
- When the iPhone is detected on the connection, the Rails application renders the partial 'foriphoneonly' exclusively for the iPhone. This trick allows you to have one URL for your web site; iPhone users will see one interface while Firefox, Safari, and IE browsers will see something different. There has been some debate on the merits of blocking iPhone specific content from Firefox and IE users but this decision is probably best left to your business department.
To get started right away, simply create a style sheet exclusively for the iPhone. You can specify specific media type declarations to focus our CSS to appear only on iPhones:
<link media="only screen and (max-device-width: 480px)"
href="iPhone.css" type="text/css" rel="stylesheet" />
You have to special case the if
statement so that IE will render the CSS correct and process the media type declaration.