Created
October 5, 2010 12:44
-
-
Save sinefunc/611485 to your computer and use it in GitHub Desktop.
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
# Usage: | |
browser.ie6? | |
browser.gecko? | |
browser.chrome? and browser.linux? | |
# In the wild: | |
<% if browser.ios? %> | |
<script src="/js/iphone.js"></script> | |
<% end %> | |
# Or maybe: | |
get '/' do | |
redirect '/touch' if browser.ios? | |
end |
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 Main | |
helpers do | |
def browser | |
UserAgent.new(env['HTTP_USER_AGENT']) | |
end | |
end | |
end |
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 UserAgent | |
def initialize(ua) | |
@ua_string = ua | |
@ua = ua.scan(%r{([^ /]+)/([^ ]+)(?: \(([^)]+)\))?}).map { |r| { :product => r[0], :version => r[1], :details => (r[2] ? r[2].split(';') : nil) } } | |
end | |
# Browsers | |
def webkit?() product?('AppleWebKit'); end | |
def chrome?() product?('Chrome'); end | |
def safari?() product?('Safari'); end | |
def ios?() product?('Safari') && product?('Mobile') end | |
def gecko?() product?('Gecko'); end | |
def firefox?() product?('Firefox'); end | |
def opera?() product?('Opera'); end | |
def ie?() detail?(/^MSIE/, 'Mozilla'); end | |
# OS's | |
def linux?() detail?(/^Linux/, 'Mozilla'); end | |
def windows?() detail?(/^Windows/, 'Mozilla'); end | |
def osx?() detail?(/^Intel Mac OS X/, 'Mozilla'); end | |
def mac?() detail?(/^Macintosh/, 'Mozilla') || osx?; end | |
# IE | |
def ie9?() detail?('MSIE 9.0', 'Mozilla'); end | |
def ie8?() detail?('MSIE 8.0', 'Mozilla'); end | |
def ie7?() detail?(/^MSIE 7.0/, 'Mozilla'); end | |
def ie6?() detail?(/^MSIE 6/, 'Mozilla'); end | |
def to_s() @ua_string; end | |
def inspect() @ua.inspect; end | |
# Checks for, say, 'Gecko' in 'Gecko/3.9.82' | |
def product?(str) | |
!! @ua.detect { |p| p[:product] == str } | |
end | |
# Checks for, say, 'MSIE' in 'Mozilla/5.0 (MSIE; x; x)' | |
def detail?(detail, product=nil) | |
!! @ua.detect do |p| | |
(product.nil? || product == p[:product]) && | |
!p[:details].nil? && | |
p[:details].detect { |d| d.match(detail) } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment