Simple iPhone User Agent detection with Rails
There are a lot of methods for detecting user agents, but if you just want to use a different app layout in your rails app for iPhone users, here’s how we do it.
class ApplicationController < ActionController::Base
...
layout :application_layout
# detect UA for iPhone users
def application_layout
@browser_name ||= begin
ua = request.env['HTTP_USER_AGENT'].downcase
if ua.index('iphone')
'application.iphone'
else
'application'
end
end
end
end
It’s important to note that we did have to define layout :application_layout Rails will choose this as a default, but since we have to override it’s default we’ll need to state it again here.
Now we just need those two files, application.iphone.html.erb and application.html.erb in views/layouts.