Rails检测移动设备的方式?

Joe*_*ano 27 ruby mobile ruby-on-rails

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

<% if mobile? %>
Run Code Online (Sandbox Code Playgroud)

小智 20

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


utn*_*nas 20

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

def mobile_device?
  if session[:mobile_param]
    session[:mobile_param] == "1"
  else
    request.user_agent =~ /Mobile|webOS/
  end
end
Run Code Online (Sandbox Code Playgroud)

或者您可以使用宝石来检测移动设备

  • 看起来active_device处于非活动状态. (4认同)

Fla*_*che 9

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
Run Code Online (Sandbox Code Playgroud)

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

<% if mobile_device == "mobile" %>
  Show something for mobile users.
<% end %>
Run Code Online (Sandbox Code Playgroud)