在Rails 3中检测用户操作系统的最简单方法是什么?

简单的Rails应用程序,主要是脚手架。 我想检测用户是否使用Android或iPhone访问我的应用程序。 最简单的方法是什么?

if request.env['HTTP_USER_AGENT'].downcase.match(/android|iphone/) puts "yup, its mobile" end 

我知道这个问题很旧,但是如果这对其他人有帮助,我会在application_controller.rb使用这个方法自动将格式设置为:mobile

 before_filter :detect_mobile protected def detect_mobile request.format = :mobile if mobile? end def mobile? request.user_agent =~ /iPhone|iPad|Android/i end 

mobile? 方法是独立的,因此如果您需要为移动浏览器执行某种条件逻辑,您也可以在自己的控制器中使用它。

  def getBrowser(bt) rs=false ua=request.env['HTTP_USER_AGENT'].downcase isOpera = ua.index('opera') ? true : false isSafari = (ua =~ /webkit|khtml/) ? true : false isSafari3 = (ua.index('webkit/5') ? true : false isGecko = (!isSafari and ua.index('gecko')) ? true : false isGecko3 = (!isSafari and ua.index('rv:1.9')) ? true : false isIE = (!isOpera and ua.index('msie')) ? true : false isIE7 = (!isOpera and ua.index('msie 7')) ? true : false case bt when 0 #isKonqueror if ua.index('konqueror') then rs=true end when 1 #isOpera rs=isOpera when 2 #isSafari rs=isSafari when 3 #isSafari2 rs=isSafari && !isSafari3 when 4 #isSafari3 rs=isSafari3 when 5 #isIE rs=isIE when 6 #isIE6 rs=isIE && !isIE7 when 7 #isIE7 rs=isIE7 when 8 #isGecko rs=isGecko when 9 #isGecko2 rs=isGecko && !isGecko3 when 10 #isGecko3 rs=isGecko3 when 11 #isWindows if ua.index('windows') or ua.index('win32') then rs=true end when 12 #isMac if ua.index('macintosh') or ua.index('mac os x') then rs=true end when 13 #isAir if ua.index('adobeair') then rs=true end when 14 #isLinux if ua.index('linux') then rs=true end when 15 #isSecure s = request.env['SERVER_PROTOCOL'].downcase if s.index('https') then rs=true end end rs end 

http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/8fa57719fd9316e1

user_agent gem对于移动与桌面……以及浏览器版本非常有用。 但是没有为OS https://github.com/josh/useragent做任何事情