Skip to content

Instantly share code, notes, and snippets.

@sinefunc
Created October 5, 2010 12:44
Show Gist options
  • Save sinefunc/611485 to your computer and use it in GitHub Desktop.
Save sinefunc/611485 to your computer and use it in GitHub Desktop.
# 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
class Main
helpers do
def browser
UserAgent.new(env['HTTP_USER_AGENT'])
end
end
end
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