Posted By

chrisaiv on 05/22/10


Tagged

rails iphone


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

t9md
endorfin
kukhtenko


Rails: iPhone Detection


 / Published in: Rails
 

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.

  1. #############################
  2. # 1. ipHone Detection in ApplicationController
  3. #############################
  4. class ApplicationController < ActionController::Base
  5. helper :all # include all helpers, all the time
  6. protect_from_forgery # See ActionController::RequestForgeryProtection for details
  7.  
  8. before_filter :detect_iphone_request
  9.  
  10. protected
  11. def detect_iphone_request
  12. request.format = :iphone if iphone_request?
  13. end
  14.  
  15. def iphone_request?
  16. # request.subdomains.first == 'iphone'
  17. request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Mobile\/.+Safari)/]
  18. end
  19. end
  20.  
  21. #############################
  22. # 2. Add this to /config/initializers/mime_types.rb
  23. #############################
  24. Mime::Type.register_alias "text/html", :iphone
  25.  
  26. #############################
  27. # 3. Make sure your respond_to on your controllers look like this
  28. #############################
  29. class SomeController < ApplicationController
  30. #Example
  31. def index
  32. #do something
  33. respond_to do |format|
  34. format.html # index.html.erb
  35. format.iphone #index.iphone.erb
  36. end
  37. end
  38. end

Report this snippet  

You need to login to post a comment.