Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check device type via user_agent (rails)

I want to know whether my users are browsing a page in my rails application with

  • a tablet or
  • a mobile device or
  • a desktop computer

I digged through many different solutions. Here are my favorites:

  1. The ua-parser gem: https://github.com/ua-parser/uap-ruby which seems to be very clean but unfortunately it always plots Other when I use parsed_string.device - I can detect the OS and browser with it very well.
  2. Writing it from scratch

Writing from scratch ended up in sth like this:

if request.user_agent.downcase.match(/mobile|android|iphone|blackberry|iemobile|kindle/)
  @os = "mobile"
elsif request.user_agent.downcase.match(/ipad/)
  @os = "tablet"
elsif request.user_agent.downcase.match(/mac OS|windows/)
  @os = "desktop"
end

However, what I miss is a complete documentation of the user agent 'device' definitions.

For example: What patterns do I need to look at if my user is browsing on a tablet/mobile device or desktop? I can't just guess and checking e.g. the ua-parser regex is not helping me either (very complicated): https://github.com/tobie/ua-parser/blob/master/regexes.yaml

Is there any simple solution to solve my problem? How does google analytics do it? I tried to research but could not find it. They're also displaying devices (desktop/tablet/mobile).

like image 737
DonMB Avatar asked Sep 16 '15 06:09

DonMB


1 Answers

The browser gem has a suggestion to do this, but until that is added you could still use the gem to figure it out by using browser.device?

like image 129
rmcsharry Avatar answered Nov 05 '22 12:11

rmcsharry