【问题标题】:Check device type via user_agent (rails)通过 user_agent (rails) 检查设备类型
【发布时间】:2015-09-16 06:56:07
【问题描述】:
我想知道我的用户是否正在使用我的 rails 应用程序浏览页面
我研究了许多不同的解决方案。以下是我的最爱:
- ua-parser gem:https://github.com/ua-parser/uap-ruby,看起来很干净,但不幸的是,当我使用
parsed_string.device 时,它总是绘制Other - 我可以很好地检测操作系统和浏览器。
- 从头开始编写
从头开始写作最终是这样的:
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
有什么简单的方法可以解决我的问题吗?
谷歌分析是如何做到的?我试图研究但找不到。他们还展示设备(台式机/平板电脑/移动设备)。
【问题讨论】:
标签:
ruby-on-rails
user-agent
【解决方案2】:
我正在寻找第二个选项,因为我需要它尽可能精益求精。 User-Agent 字符串中有很多我不需要的信息。而且我不想要一个试图解析它的函数。很简单:机器人、台式机、平板电脑、移动设备和其他。
阅读内容有点多,但我正在寻找使用 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'];