Return to Snippet

Revision: 27105
at May 22, 2010 13:59 by chrisaiv


Initial Code
#############################
# 1. ipHone Detection in ApplicationController
#############################
class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details
  
  before_filter :detect_iphone_request
  
  protected  
  def detect_iphone_request
    request.format = :iphone if iphone_request?
  end
  
  def iphone_request?
#     request.subdomains.first == 'iphone'
    request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Mobile\/.+Safari)/]
  end  
end

#############################
# 2. Add this to /config/initializers/mime_types.rb
#############################
Mime::Type.register_alias "text/html", :iphone

#############################
# 3. Make sure your respond_to on your controllers look like this
#############################
class SomeController < ApplicationController
  #Example
  def index
   #do something
    respond_to do |format|
      format.html # index.html.erb
      format.iphone #index.iphone.erb
     end
  end
end

Initial URL


Initial Description
Use this as a way to detect iPhone users using Rails 2+.  This should live in your /controllers/application_controller.rb (class ApplicationController < ActionController::Base).  You also need to modify your mime type.

Initial Title
Rails: iPhone Detection

Initial Tags
rails, iphone

Initial Language
Rails