Class: RSpec::Support::ComparableVersion

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/rspec/support/comparable_version.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ ComparableVersion

Returns a new instance of ComparableVersion.



9
10
11
# File 'lib/rspec/support/comparable_version.rb', line 9

def initialize(string)
  @string = string
end

Instance Attribute Details

#stringObject (readonly)

Returns the value of attribute string.



7
8
9
# File 'lib/rspec/support/comparable_version.rb', line 7

def string
  @string
end

Instance Method Details

#<=>(other) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rspec/support/comparable_version.rb', line 13

def <=>(other)
  other = self.class.new(other) unless other.is_a?(self.class)

  return 0 if string == other.string

  longer_segment_count = [self, other].map { |version| version.segments.count }.max

  longer_segment_count.times do |index|
    self_segment = segments[index] || 0
    other_segment = other.segments[index] || 0

    if self_segment.class == other_segment.class
      result = self_segment <=> other_segment
      return result unless result == 0
    else
      return self_segment.is_a?(String) ? -1 : 1
    end
  end

  0
end

#segmentsObject



35
36
37
38
39
40
41
42
43
# File 'lib/rspec/support/comparable_version.rb', line 35

def segments
  @segments ||= string.scan(/[a-z]+|\d+/i).map do |segment|
    if segment =~ /\A\d+\z/
      segment.to_i
    else
      segment
    end
  end
end