Class: Epuber::Version

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/epuber/vendor/version.rb

Constant Summary collapse

VERSION_RE =
/\A[0-9]+(\.[0-9a-zA-Z]+)*\z/.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(version) ⇒ Version

Returns a new instance of Version.

Parameters:

  • version (String, Numeric)

    input primitive value for version

Raises:

  • (StandardError)


26
27
28
29
30
# File 'lib/epuber/vendor/version.rb', line 26

def initialize(version)
  raise StandardError, "Malformed version number string #{version}" unless self.class.correct?(version)

  @version = version.to_s.strip
end

Instance Attribute Details

#versionObject (readonly)

Returns the value of attribute version.



21
22
23
# File 'lib/epuber/vendor/version.rb', line 21

def version
  @version
end

Class Method Details

.correct?(version) ⇒ Boolean

True if the version string matches RubyGems’ requirements.

Returns:

  • (Boolean)


17
18
19
# File 'lib/epuber/vendor/version.rb', line 17

def self.correct?(version)
  version.to_s =~ VERSION_RE
end

Instance Method Details

#<=>(other) ⇒ Numeric

Compares this version with other returning -1, 0, or 1 if the other version is larger, the same, or smaller than this one.

Returns:

  • (Numeric)


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
# File 'lib/epuber/vendor/version.rb', line 52

def <=>(other)
  return unless other.is_a?(Version) || other.is_a?(String) || other.is_a?(Float) || other.is_a?(Integer)

  other = Version.new(other) unless other.is_a?(Version)

  return 0 if @version == other.version

  lhsegments = segments
  rhsegments = other.segments

  lhsize = lhsegments.size
  rhsize = rhsegments.size
  limit  = [lhsize, rhsize].max - 1

  i = 0

  while i <= limit
    lhs = lhsegments[i] || 0
    rhs = rhsegments[i] || 0
    i += 1

    next      if lhs == rhs
    return -1 if lhs.is_a?(String) && number?(rhs)
    return  1 if number?(lhs) && rhs.is_a?(String)

    return lhs <=> rhs
  end

  0
end

#segmentsArray<Numeric>

Returns:

  • (Array<Numeric>)


34
35
36
37
38
# File 'lib/epuber/vendor/version.rb', line 34

def segments
  @segments ||= @version.scan(/[0-9]+|[a-z]+/i).map do |s|
    /^\d+$/ =~ s ? s.to_i : s
  end
end

#to_sString

Returns:

  • (String)


42
43
44
# File 'lib/epuber/vendor/version.rb', line 42

def to_s
  segments.join('.').to_s
end