File: version.rb

package info (click to toggle)
ruby-useragent 0.16.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 164 kB
  • sloc: ruby: 1,150; makefile: 2
file content (104 lines) | stat: -rw-r--r-- 1,939 bytes parent folder | download | duplicates (3)
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
class UserAgent
  class Version
    include ::Comparable

    def self.new(obj = nil)
      case obj
      when Version
        obj
      when String
        super
      when NilClass
        super("")
      else
        raise ArgumentError, "invalid value for Version: #{obj.inspect}"
      end
    end

    def initialize(str)
      @str = str

      if @str =~ /^\s*$/
        @nil        = true
        @sequences  = []
        @comparable = false
      elsif str =~ /^\d+$/ || str =~ /^\d+\./
        @nil        = false
        @sequences  = str.scan(/\d+|[A-Za-z][0-9A-Za-z-]*$/).map { |s| s =~ /^\d+$/ ? s.to_i : s }
        @comparable = true
      else
        @nil        = false
        @sequences  = [str]
        @comparable = false
      end
    end

    def nil?
      @nil
    end

    def to_a
      @sequences.dup
    end

    def to_str
      @str.dup
    end

    def eql?(other)
      other.is_a?(self.class) && to_s == other.to_s
    end

    def ==(other)
      case other
      when Version
        eql?(other)
      when String
        eql?(self.class.new(other))
      when NilClass
        nil?
      else
        false
      end
    end

    def <=>(other)
      case other
      when Version
        if @comparable
          ([0]*6).zip(to_a, other.to_a).each do |dump, a, b|
            a ||= 0
            b ||= 0

            if a.is_a?(String) && b.is_a?(Integer)
              return -1
            elsif a.is_a?(Integer) && b.is_a?(String)
              return 1
            elsif a == b
              next
            else
              return a <=> b
            end
          end
          0
        elsif to_s == other.to_s
          return 0
        else
          return -1
        end
      when String, NilClass
        self <=> self.class.new(other)
      else
        nil
      end
    end

    def to_s
      to_str
    end

    def inspect
      "#<#{self.class} #{to_s}>"
    end
  end
end