Ruby-on-rails Rails 检测移动设备的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29068869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails way to detect mobile device?
提问by Joe Morano
Is there a "rails way" to detect whether the user is using a mobile device? What I mean is a method I can use in erb, something like this:
是否有“rails 方式”来检测用户是否正在使用移动设备?我的意思是我可以在 erb 中使用的方法,如下所示:
<% if mobile? %>
采纳答案by utnas
You can do it that way by defining a function like below:
您可以通过定义如下函数来做到这一点:
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile|webOS/
end
end
Or you can use gems to detect mobile devices like
或者您可以使用 gems 来检测移动设备,例如
回答by askl56
回答by Flavio Wuensche
In application_helper.rb:
在application_helper.rb:
def mobile_device
agent = request.user_agent
return "tablet" if agent =~ /(tablet|ipad)|(android(?!.*mobile))/i
return "mobile" if agent =~ /Mobile/
return "desktop"
end
Then you can use it in your views:
然后你可以在你的视图中使用它:
<% if mobile_device == "mobile" %>
Show something for mobile users.
<% end %>
回答by Maxo
I would suggest checking out device_detector, which is quite fast and easy to deploy. You just have to pass user_agent string to it, which can be done using request.user_agent for Rails 5:
我建议查看 device_detector,它非常快速且易于部署。您只需要将 user_agent 字符串传递给它,这可以使用 Rails 5 的 request.user_agent 来完成:
@user_agent = request.user_agent
@client = DeviceDetector.new(@user_agent)
@client.device_type
Note: Device types can be one of the following: desktop, smartphone, tablet, console, portable media player, tv, car browser, camera
注意:设备类型可以是以下之一:台式机、智能手机、平板电脑、控制台、便携式媒体播放器、电视、汽车浏览器、相机
回答by Chidozie Nnachor
You can solve this too by simply including<meta name="viewport" content="width=device-width, initial-scale=1.0">on the application.html.erbheader tag
您也可以通过简单地包含<meta name="viewport" content="width=device-width, initial-scale=1.0">在application.html.erb标题标签上来解决这个问题
As long as your site is responsive (e.g. using Bootstrap), you should be fine.
只要您的网站是响应式的(例如使用 Bootstrap),您应该没问题。

