Class: Version

Inherits:
Array
  • Object
show all
Includes:
Comparable
Defined in:
lib/caruby/helpers/version.rb

Overview

A Version is an Array of version major and minor components that is comparable to another version identifier based on a precedence relationship.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*params) ⇒ Version

Creates a new Version from the given version components and optional predecessor.

Examples:

alpha = Version.new(1, '1alpha')
Version.new(1, 1, alpha) > alpha #=> true


13
14
15
16
# File 'lib/caruby/helpers/version.rb', line 13

def initialize(*params)
  @predecessor = params.pop if self.class === params.last
  super(params)
end

Instance Attribute Details

#predecessorObject (readonly)

Returns the value of attribute predecessor.



6
7
8
# File 'lib/caruby/helpers/version.rb', line 6

def predecessor
  @predecessor
end

Instance Method Details

#<=>(other) ⇒ Object

Returns the comparison of this version identifier to the other version identifier as follows:

  • if this version can be compared to other via the predecessor graph, then return that comparison result

  • otherwise, return a component-wise comparison

Examples:

beta = Version.new(1, '1beta')
Version.new(1) < beta > #=> true
Version.new(1, 1) < beta #=> true
Version.new(1, 1, beta) > beta #=> true

Raises:

  • (ArgumentError)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/caruby/helpers/version.rb', line 27

def <=>(other)
  return 0 if equal?(other)
  raise ArgumentError.new("Comparand is not a #{self.class}: #{other}") unless self.class === other
  return -1 if other.predecessor == self
  return 1 unless predecessor.nil? or predecessor < other
  each_with_index do |component, index|
    return 1 unless index < other.length
    other_component = other[index]
    if String === other_component then
      component = component.to_s
    elsif String === component
      other_component = other_component.to_s
    end
    cmp = (component <=> other_component)
    return cmp unless cmp.zero?
  end
  length < other.length ? -1 : 0
end