Rails 3 detect request coming from mobile clients

不羁岁月 提交于 2019-12-19 08:00:23

问题


My setup: Rails 3.0.9, Ruby 1.9.2

My app needs to serve up a mobile vs. web layout depending on the request's origin. I need to support all the major mobile client front-ends like iPhone, Android, Blackberry, etc. What's the simplest way to detect this in my code?


回答1:


The easiest way to do it is parse request.user_agent by RegEx /Mobile|webOS/. Mobile/Full version variable can be saved into session, and helper will be useful to include mobile 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 is a step-by-step guide for you.




回答2:


It will return User Agent.

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


来源:https://stackoverflow.com/questions/7069054/rails-3-detect-request-coming-from-mobile-clients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!