Rails 检测移动设备的方法?
Rails way to detect mobile device?
有没有"rails way"检测用户是否在使用移动设备?我的意思是我可以在 erb 中使用的方法,像这样:
<% if mobile? %>
使用browsergem。您可以通过自定义 user_agent 检测浏览器。
您可以通过定义如下函数来实现:
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile|webOS/
end
end
或者你可以使用 gems 来检测像
这样的移动设备
您也可以通过在 application.html.erb
header 标签
上简单地 including <meta name="viewport" content="width=device-width, initial-scale=1.0">
来解决这个问题
只要您的网站是响应式的(例如使用 Bootstrap),您应该没问题。
在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 字符串传递给它,这可以使用 request.user_agent for Rails 5:
@user_agent = request.user_agent
@client = DeviceDetector.new(@user_agent)
@client.device_type
注意:设备类型可以是以下之一:台式机、智能手机、平板电脑、游戏机、便携式媒体播放器、电视、车载浏览器、相机
有没有"rails way"检测用户是否在使用移动设备?我的意思是我可以在 erb 中使用的方法,像这样:
<% if mobile? %>
使用browsergem。您可以通过自定义 user_agent 检测浏览器。
您可以通过定义如下函数来实现:
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile|webOS/
end
end
或者你可以使用 gems 来检测像
这样的移动设备您也可以通过在 application.html.erb
header 标签
<meta name="viewport" content="width=device-width, initial-scale=1.0">
来解决这个问题
只要您的网站是响应式的(例如使用 Bootstrap),您应该没问题。
在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 字符串传递给它,这可以使用 request.user_agent for Rails 5:
@user_agent = request.user_agent
@client = DeviceDetector.new(@user_agent)
@client.device_type
注意:设备类型可以是以下之一:台式机、智能手机、平板电脑、游戏机、便携式媒体播放器、电视、车载浏览器、相机