Rails浏览器检测方法

alv*_*spo 51 ruby user-agent ruby-on-rails browser-detection

嘿大家,我想知道行业中哪些方法是Rails中的浏览器检测标准?是否有某个宝石,库或示例代码可以帮助确定浏览器并将类或ID应用于(X)HTML的body元素?谢谢,我只是想知道每个人使用什么以及是否有可接受的方法来做到这一点?

我知道我们可以获取user.agent并解析该字符串,但我不确定这是否是一种可接受的浏览器检测方式.

另外,我不打算在这里讨论功能检测,我已经在StackOverflow上阅读了多个答案,我要求的就是你们所做的.

[UPDATE]

所以感谢GitHub上的faunzy,我对Rails中的用户代理进行了一些了解,但是仍然不确定这是否是在Rails 3中进行此操作的最佳方式.但这就是我所得到的远:

def users_browser
user_agent =  request.env['HTTP_USER_AGENT'].downcase 
@users_browser ||= begin
  if user_agent.index('msie') && !user_agent.index('opera') && !user_agent.index('webtv')
                'ie'+user_agent[user_agent.index('msie')+5].chr
    elsif user_agent.index('gecko/')
        'gecko'
    elsif user_agent.index('opera')
        'opera'
    elsif user_agent.index('konqueror')
        'konqueror'
    elsif user_agent.index('ipod')
        'ipod'
    elsif user_agent.index('ipad')
        'ipad'
    elsif user_agent.index('iphone')
        'iphone'
    elsif user_agent.index('chrome/')
        'chrome'
    elsif user_agent.index('applewebkit/')
        'safari'
    elsif user_agent.index('googlebot/')
        'googlebot'
    elsif user_agent.index('msnbot')
        'msnbot'
    elsif user_agent.index('yahoo! slurp')
        'yahoobot'
    #Everything thinks it's mozilla, so this goes last
    elsif user_agent.index('mozilla/')
        'gecko'
    else
        'unknown'
    end
    end

    return @users_browser
end
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 59

浏览器的宝石是专为在Rails的浏览器检测而设计的.


Chr*_*ssl 23

在GitHub上有库ruby库:https://github.com/gshutler/useragent

我自己使用它,它到目前为止的广告工作.对于您的用例,您可以从Rails项目中的帮助器方法或类似的东西中调用库.

也就是说,我不完全确定是否HTTP_USER_AGENT暴露于Rails辅助方法.如果未公开,您可以始终将控制器方法公开为帮助程序(通过使用AbstractController::Helpers::ClassMethods#helper_method).

  • 我很好奇......你在你的图书馆版本中添加了什么?源代码在某处可用吗? (4认同)

far*_*noy 5

试试request.env['HTTP_USER_AGENT'],这将返回您客户的用户代理.HubertŁępicki还发布了一个快速帮手