Skip to content

Instantly share code, notes, and snippets.

@shybovycha
Forked from tubalmartin/mobile_detector.php
Created November 14, 2012 13:53
Show Gist options
  • Save shybovycha/4072225 to your computer and use it in GitHub Desktop.
Save shybovycha/4072225 to your computer and use it in GitHub Desktop.
Lightweight detector of mobile devices, OSs & browsers (Ruby)
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