Joe Morano
Joe Morano

Reputation: 1895

Rails way to detect mobile device?

Is there a "rails way" to detect whether the user is using a mobile device? What I mean is a method I can use in erb, something like this:

<% if mobile? %>

Upvotes: 37

Views: 35902

Answers (5)

Flavio Wuensche
Flavio Wuensche

Reputation: 10396

In application_helper.rb:

def device
  agent = request.user_agent
  return "tablet" if agent =~ /(tablet|ipad)|(android(?!.*mobile))/i
  return "mobile" if agent =~ /Mobile/
  return "desktop"
end

Then you can use it in your views:

<% if device == "mobile" %>
  Show something for mobile users.
<% end %>

Upvotes: 20

Maxo
Maxo

Reputation: 538

I would suggest checking out device_detector, which is quite fast and easy to deploy. You just have to pass user_agent string to it, which can be done using request.user_agent for Rails 5:

@user_agent = request.user_agent

@client = DeviceDetector.new(@user_agent)

@client.device_type 

Note: Device types can be one of the following: desktop, smartphone, tablet, console, portable media player, tv, car browser, camera

https://github.com/podigee/device_detector

Upvotes: 4

Chidozie Nnachor
Chidozie Nnachor

Reputation: 902

You can solve this too by simply including <meta name="viewport" content="width=device-width, initial-scale=1.0"> on the application.html.erb header tag

As long as your site is responsive (e.g. using Bootstrap), you should be fine.

Upvotes: -1

utnas
utnas

Reputation: 448

You can do it that way by defining a function like below:

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

Or you can use gems to detect mobile devices like

Upvotes: 25

user4674730
user4674730

Reputation:

Use browser gem. You are able to detect the browser by the custom user_agent.

Upvotes: 22

Related Questions