Sha256: 22eb6b0d3285f46e917cc402b457b8bc6edc0534f6b6564bb79f21203242ffe2

Contents?: true

Size: 1.83 KB

Versions: 24

Compression:

Stored size: 1.83 KB

Contents

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{
    ^([^/\s]+)        # Product
    /?([^\s]*)        # Version
    (\s\(([^\)]*)\))? # Comment
  }x.freeze

  DEFAULT_USER_AGENT = "Mozilla/4.0 (compatible)"

  def self.parse(string)
    if string.nil? || string == ""
      string = DEFAULT_USER_AGENT
    end

    agents = []
    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)
    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 = nil
    end

    if comment.respond_to?(:split)
      @comment = comment.split("; ")
    else
      @comment = comment
    end
  end

  include Comparable

  # Any comparsion between two user agents with different products will
  # always return false.
  def <=>(other)
    if @product == other.product
      if @version && other.version
        @version <=> other.version
      else
        0
      end
    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 && @comment
      "#{@product}/#{@version} (#{@comment.join("; ")})"
    elsif @product && @version
      "#{@product}/#{@version}"
    elsif @product && @comment
      "#{@product} (#{@comment.join("; ")})"
    else
      @product
    end
  end
end

Version data entries

24 entries across 24 versions & 3 rubygems

Version Path
useragent-0.8.3 lib/user_agent.rb
useragent-0.8.2 lib/user_agent.rb
useragent-0.8.1 lib/user_agent.rb
useragent-0.8.0 lib/user_agent.rb
useragent-0.7.0 lib/user_agent.rb
friendlyfashion-useragent-0.6.1.1 lib/user_agent.rb
friendlyfashion-useragent-0.6.1 lib/user_agent.rb
useragent-0.6.0 lib/user_agent.rb
useragent-0.5.0 lib/user_agent.rb
useragent-0.4.16 lib/user_agent.rb
useragent-0.4.15 lib/user_agent.rb
useragent-0.4.14 lib/user_agent.rb
useragent-0.4.13 lib/user_agent.rb
useragent-0.4.12 lib/user_agent.rb
useragent-0.4.11 lib/user_agent.rb
useragent-0.4.10 lib/user_agent.rb
useragent-0.4.9 lib/user_agent.rb
useragent-0.4.8 lib/user_agent.rb
useragent-0.4.7 lib/user_agent.rb
useragent-0.4.6 lib/user_agent.rb