通过user_agent检查设备类型(rails)

时间:2015-09-16 06:56:08

标签: ruby-on-rails user-agent

我想知道我的用户是否正在使用

浏览我的rails应用程序中的页面
  • 平板电脑或
  • 移动设备或
  • 台式电脑

我深入研究了许多不同的解决方案。这是我的最爱:

  1. ua-parser gem:https://github.com/ua-parser/uap-ruby看起来非常干净但不幸的是,当我使用Other时它总是绘制parsed_string.device - 我可以很好地检测操作系统和浏览器
  2. 从头开始编写
  3. 从头开始写作就像这样:

    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
    

    然而,我想念的是用户代理'设备的完整文档。定义

    例如: 如果我的用户在平板电脑/移动设备或桌面上浏览,我需要查看哪些模式?我无法猜测和检查,例如ua-parser正则表达式也没有帮助我(非常复杂):https://github.com/tobie/ua-parser/blob/master/regexes.yaml

    有什么简单的解决方案可以解决我的问题吗? 谷歌分析如何做到这一点?我试图研究但找不到它。他们还会显示设备(桌面/平板电脑/手机)。

2 个答案:

答案 0 :(得分:0)

browser gemsuggestion来执行此操作,但在添加之前,您仍然可以使用gem来使用browser.device?

来计算出来

答案 1 :(得分:0)

我正在寻找第二种选择,因为我需要它尽可能精益求精。用户代理字符串中有很多信息,我不需要。而且我不想要一个试图解析它的函数。简单地说:机器人,桌面设备,平板电脑,移动设备等。

要阅读的内容很多,但我正在使用this extensive list寻找关键字。

到目前为止,以下关键字似乎对我有用。它是PHP中的常规表达,但你会得到这个想法。

//try to find crawlers
//  https://developers.whatismybrowser.com/useragents/explore/software_type_specific/crawler/
if (preg_match('/(bot\/|spider|crawler|slurp|pinterest|favicon)/i', $userAgent) === 1)
  return ['type' => 'crawler'];

//try to find tablets
//  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/tablet/
//  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/ebook-reader/
if (preg_match('/(ipad| sm-t| gt-p| gt-n|wt19m-fi|nexus 7| silk\/|kindle| nook )/i', $userAgent) === 1)
  return ['type' => 'tablet'];

//try to find mobiles
//  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/mobile/
//  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/phone/
if (preg_match('/(android|iphone|mobile|opera mini|windows phone|blackberry|netfront)/i', $userAgent) === 1)
  return ['type' => 'mobile'];

//try to find desktops
//  https://developers.whatismybrowser.com/useragents/explore/hardware_type_specific/computer/
if (preg_match('/(windows nt|macintosh|x11; linux|linux x86)/i', $userAgent) === 1)
  return ['type' => 'desktop'];

return ['type' => 'other'];