-
-
Save shybovycha/4072225 to your computer and use it in GitHub Desktop.
Lightweight detector of mobile devices, OSs & browsers (Ruby)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MobileDetector | |
# pass request.env for Rails 3.2 | |
def initialize(headers) | |
@headers = headers | |
end | |
def get_mobile_os | |
regexps = { | |
#mobile OSs | |
'ios' => 'ip(hone|ad|od)', | |
'android' => 'android', | |
'webos' => '(web|hpw)os', | |
'palmos' => 'palm(\s?os|source)', | |
'windows' => 'windows (phone|ce)', | |
'symbian' => 'symbian(\s?os|)|symbos', | |
'bbos' => 'blackberry(.*?version\/\d+|\d+\/\d+)', | |
'bada' => 'bada' | |
} | |
return nil unless @headers['HTTP_USER_AGENT'] | |
regexps.each do |name, re| | |
return name.to_sym if @headers['HTTP_USER_AGENT'] =~ Regexp.new(re, Regexp::IGNORECASE) | |
end | |
nil | |
end | |
def mobile? | |
regexps = { | |
#mobile browsers | |
'opera_mobile' => 'opera (mobi|mini)', # Opera Mobile or Mini | |
'webkit_mobile' => '(android|nokia|webos|hpwos|blackberry).*?webkit|webkit.*?(mobile|kindle|bolt|skyfire|dolfin|iris)', # Webkit mobile | |
'firefox_mobile' => 'fennec', # Firefox mobile | |
'ie_mobile' => 'iemobile|windows ce', # IE mobile | |
'netfront' => 'netfront|kindle|psp|blazer|jasmine', # Netfront | |
'uc_browser' => 'ucweb' # UC browser | |
} | |
return nil unless @headers['HTTP_USER_AGENT'] | |
regexps.each do |name, re| | |
return true if @headers['HTTP_USER_AGENT'] =~ Regexp.new(re, Regexp::IGNORECASE) | |
end | |
false | |
end | |
def desktop? | |
!mobile? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment