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
|
require 'user_agent/comparable'
require 'user_agent/browsers'
require 'user_agent/operating_systems'
require 'user_agent/version'
class UserAgent
# http://www.texsoft.it/index.php?m=sw.php.useragent
MATCHER = %r{
^['"]* # Possible opening quote(s)
([^/\s]+) # Product
/?([^\s,]*) # Version
(\s\(([^\)]*)\)|,gzip\(gfe\))? # Comment
}x.freeze
DEFAULT_USER_AGENT = "Mozilla/4.0 (compatible)"
def self.parse(string)
if string.nil? || string.strip == ""
string = DEFAULT_USER_AGENT
end
agents = Browsers::Base.new
while m = string.to_s.match(MATCHER)
agents << new(m[1], m[2], m[4])
string = string[m[0].length..-1].strip
end
Browsers.extend(agents)
end
attr_reader :product, :version, :comment
def initialize(product, version = nil, comment = nil)
if product
@product = product
else
raise ArgumentError, "expected a value for product"
end
if version && !version.empty?
@version = Version.new(version)
else
@version = Version.new
end
if comment.respond_to?(:split)
@comment = comment.split("; ")
else
@comment = comment
end
end
include Comparable
def detect_comment(&block)
comment && comment.detect(&block)
end
# Any comparison between two user agents with different products will
# always return false.
def <=>(other)
if @product == other.product
@version <=> other.version
else
false
end
end
def eql?(other)
@product == other.product &&
@version == other.version &&
@comment == other.comment
end
def to_s
to_str
end
def to_str
if @product && !@version.nil? && @comment
"#{@product}/#{@version} (#{@comment.join("; ")})"
elsif @product && !@version.nil?
"#{@product}/#{@version}"
elsif @product && @comment
"#{@product} (#{@comment.join("; ")})"
else
@product
end
end
end
|