[英]What's the easiest way to detect the user's operating system in 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做任何事情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.