Rails检测移动设备的方式?

时间:2015-03-16 02:40:50

标签: ruby-on-rails ruby mobile

是否有“轨道方式”来检测用户是否正在使用移动设备?我的意思是我可以在erb中使用的方法,如下所示:

<% if mobile? %>

5 个答案:

答案 0 :(得分:20)

使用browser gem。您可以通过自定义user_agent检测浏览器。

答案 1 :(得分:18)

您可以通过定义如下函数来实现这一目标:

def mobile_device?
  if session[:mobile_param]
    session[:mobile_param] == "1"
  else
    request.user_agent =~ /Mobile|webOS/
  end
end

或者您可以使用gems来检测

等移动设备

答案 2 :(得分:5)

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

然后您可以在视图中使用它:

<% if mobile_device == "mobile" %>
  Show something for mobile users.
<% end %>

答案 3 :(得分:0)

您也可以通过简单地在<meta name="viewport" content="width=device-width, initial-scale=1.0">标头标记上including application.html.erb来解决此问题

只要您的网站具有响应能力(例如使用Bootstrap),就可以了。

答案 4 :(得分:0)

我建议您检出device_detector,它非常快速且易于部署。您只需将user_agent字符串传递给它,可以使用Rails 5的request.user_agent来完成:

@user_agent = request.user_agent

@client = DeviceDetector.new(@user_agent)

@client.device_type 

注意:设备类型可以是以下类型之一:台式机,智能手机,平板电脑,控制台,便携式媒体播放器,电视,车载浏览器,摄像头

https://github.com/podigee/device_detector

相关问题