Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 detect request coming from mobile clients

My setup: Rails 3.0.9, Ruby 1.9.2

My app needs to serve up a mobile vs. web layout depending on the request's origin. I need to support all the major mobile client front-ends like iPhone, Android, Blackberry, etc. What's the simplest way to detect this in my code?

like image 400
Bob Avatar asked Aug 15 '11 18:08

Bob


2 Answers

The easiest way to do it is parse request.user_agent by RegEx /Mobile|webOS/. Mobile/Full version variable can be saved into session, and helper will be useful to include mobile CSS:

#controller
def mobile_device?
  if session[:mobile_param]
    session[:mobile_param] == "1"
  else
    request.user_agent =~ /Mobile|webOS/
  end
end

helper_method :mobile_device?


#layout
<%= stylesheet_link_tag 'mobile' if mobile_device? %>

Railscasts 199 is a step-by-step guide for you.

like image 127
Anatoly Avatar answered Oct 12 '22 23:10

Anatoly


It will return User Agent.

request.user_agent =~ /Mobile|Blackberry|Android/ # OR WHATEVER
like image 43
fl00r Avatar answered Oct 12 '22 23:10

fl00r