Rails way to detect mobile device?

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

  • https://github.com/tscolari/mobylette
  • https://github.com/shenoudab/active_device

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


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 %>

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