【发布时间】:2015-03-16 02:40:49
【问题描述】:
是否有“rails 方式”来检测用户是否在使用移动设备?我的意思是我可以在 erb 中使用的一种方法,如下所示:
<% if mobile? %>
【问题讨论】:
标签: ruby-on-rails ruby mobile
是否有“rails 方式”来检测用户是否在使用移动设备?我的意思是我可以在 erb 中使用的一种方法,如下所示:
<% if mobile? %>
【问题讨论】:
标签: ruby-on-rails ruby mobile
您可以通过定义如下函数来做到这一点:
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile|webOS/
end
end
或者您可以使用 gems 来检测移动设备,例如
【讨论】:
使用browser 宝石。您可以通过自定义 user_agent 检测浏览器。
【讨论】:
browser.mobile??
browser 很好,但需要 > ruby 2。如果你被困在 1.9.3(像我一样),请查看 github.com/tscolari/mobylette
browser 似乎仍会在 2020 年得到维护,并且随着时间的推移只会增加使用量。
在application_helper.rb:
def device
agent = request.user_agent
return "tablet" if agent =~ /(tablet|ipad)|(android(?!.*mobile))/i
return "mobile" if agent =~ /Mobile/
return "desktop"
end
然后你可以在你的视图中使用它:
<% if device == "mobile" %>
Show something for mobile users.
<% end %>
【讨论】:
我建议查看 device_detector,它非常快速且易于部署。您只需将 user_agent 字符串传递给它,这可以使用 Rails 5 的 request.user_agent 来完成:
@user_agent = request.user_agent
@client = DeviceDetector.new(@user_agent)
@client.device_type
注意:设备类型可以是以下之一:台式机、智能手机、平板电脑、控制台、便携式媒体播放器、电视、车载浏览器、相机
【讨论】:
您也可以通过 including <meta name="viewport" content="width=device-width, initial-scale=1.0"> 上的 application.html.erb 标头标签来解决此问题
只要您的网站是响应式的(例如使用 Bootstrap),您应该没问题。
【讨论】: