在Rails 3中检测移动浏览器

Sli*_*k23 19 ruby-on-rails-3

我希望在我的应用程序中执行一些特定于移动设备的布局,并且一直在研究检测移动浏览器和提供移动特定布局的方法.

我碰到这个传来:http://www.arctickiwi.com/blog/mobile-enable-your-ruby-on-rails-site-for-small-screens

但是使用一系列关键字对我来说似乎有点脆弱.如果关键字改变怎么办?任何人遇到任何宝石或插件或更多的未来证明策略?

gsh*_*lin 28

最好的方法是使用一些受支持的插件/ gem,比如浏览器 您无法使用自定义user_agents跟踪所有浏览器.例如Opera 11.50具有以下内容user_agent:

Opera/9.80 (Android 2.3.7; Linux; Opera Mobi/ADR-1111021303; U; en-GB) Presto/2.9.201 Version/11.50
Run Code Online (Sandbox Code Playgroud)

它完全无法辨认

request.user_agent =~ /Mobile|webOS/ 
Run Code Online (Sandbox Code Playgroud)


Pan*_*kos 20

实际上,您可以使用更简单的正则表达式.此Railscast中概述了该方法,允许您加载不同的JS并为移动设备定义不同的页面交互.

基本上,您最终会得到一个只检查用户代理是否包含"Mobile"或"webOS"的函数:

def mobile_device?
  if session[:mobile_param]
    session[:mobile_param] == "1"
  else
    request.user_agent =~ /Mobile|webOS/
  end
end
Run Code Online (Sandbox Code Playgroud)