1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
|
class UserAgent
module Browsers
class Base < Array
include Comparable
def <=>(other)
if respond_to?(:browser) && other.respond_to?(:browser) &&
browser == other.browser
version <=> Version.new(other.version)
else
false
end
end
def eql?(other)
self == other
end
def to_s
to_str
end
def to_str
join(" ")
end
def application
first
end
def browser
application && application.product
end
def version
application && application.version
end
def platform
nil
end
def os
nil
end
def respond_to?(symbol, include_all = false)
detect_product(symbol) ? true : super
end
def method_missing(method, *args, &block)
detect_product(method) || super
end
def mobile?
if detect_product('Mobile') || detect_comment('Mobile')
true
elsif os =~ /Android/
true
elsif application && application.detect_comment { |c| c =~ /^IEMobile/ }
true
else
false
end
end
def bot?
# If UA has no application type, its probably generated by a
# shitty bot.
if application.nil?
true
# Match common case when bots refer to themselves as bots in
# the application comment. There are no standards for how bots
# should call themselves so its not an exhaustive method.
#
# If you want to expand the scope, override the method and
# provide your own regexp. Any patches to future extend this
# list will be rejected.
elsif comment = application.comment
comment.any? { |c| c =~ /bot/i }
elsif product = application.product
product.include?('bot')
else
false
end
end
def to_h
return unless application
hash = {
:browser => browser,
:platform => platform,
:os => os,
:mobile => mobile?,
:bot => bot?,
}
if version
hash[:version] = version.to_a
else
hash[:version] = nil
end
if comment = application.comment
hash[:comment] = comment.dup
else
hash[:comment] = nil
end
hash
end
private
def detect_product(product)
detect { |useragent| useragent.product.to_s.downcase == product.to_s.downcase }
end
def detect_comment(comment)
detect { |useragent| useragent.detect_comment { |c| c == comment } }
end
def detect_comment_match(regexp)
comment_match = nil
detect { |useragent| useragent.detect_comment { |c| comment_match = c.match(regexp) } }
comment_match
end
end
end
end
|