有没有一种“Rails方式”来检测用户是否使用移动设备?我的意思是在erb中可以使用的方法,像这样:
<% if mobile? %>
有没有一种“Rails方式”来检测用户是否使用移动设备?我的意思是在erb中可以使用的方法,像这样:
<% if mobile? %>
您可以通过定义一个如下的函数来实现:
def mobile_device?
if session[:mobile_param]
session[:mobile_param] == "1"
else
request.user_agent =~ /Mobile|webOS/
end
end
或者您可以使用 gem 检测移动设备,例如
使用 browser gem。你可以通过自定义user_agent检测浏览器。
browser.mobile?
吗? - Joe Moranobrowser
很好,但需要> ruby 2。如果你卡在1.9.3上(就像我一样),可以查看https://github.com/tscolari/mobylette。 - Alex Moore-Niemi在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 %>
@user_agent = request.user_agent
@client = DeviceDetector.new(@user_agent)
@client.device_type
application.html.erb
的头部标签中 包含 <meta name="viewport" content="width=device-width, initial-scale=1.0">
来解决这个问题。