Rails 3检测来自移动客户端的请求

时间:2011-08-15 18:35:03

标签: ruby-on-rails ruby-on-rails-3 mobile

我的设置:Rails 3.0.9,Ruby 1.9.2

我的应用需要根据请求的来源提供移动设备与网络布局。我需要支持所有主要的移动客户端前端,如iPhone,Android,Blackberry等。在我的代码中检测这个的最简单方法是什么?

2 个答案:

答案 0 :(得分:8)

最简单的方法是通过RegEx / Mobile | webOS / 解析 request.user_agent 。 移动/完整版变量可以保存到会话中,帮助程序对于包含移动CSS很有用:

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

helper_method :mobile_device?


#layout
<%= stylesheet_link_tag 'mobile' if mobile_device? %>

Railscasts 199是您的分步指南。

答案 1 :(得分:7)

它将返回用户代理。

request.user_agent =~ /Mobile|Blackberry|Android/ # OR WHATEVER