Class: Babushka::VersionStr

Inherits:
Object show all
Includes:
Comparable
Defined in:
lib/babushka/version_str.rb

Constant Summary

GemVersionOperators =
%w[= == != > < >= <= ~>].freeze

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (VersionStr) initialize(str)

A new instance of VersionStr



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/babushka/version_str.rb', line 20

def initialize str
  @operator, @version = str.strip.scan(/^([^\s\w\-\.]+)?\s*v?([\w\-\.]+)$/i).first

  if !(@operator.nil? || GemVersionOperators.include?(@operator))
    raise InvalidVersionOperator, "VersionStr.new('#{str}'): invalid operator '#{@operator}'."
  elsif @version.nil?
    raise InvalidVersionStr, "VersionStr.new('#{str}'): couldn't parse a version number."
  else
    @pieces = @version.strip.scan(/\d+|[a-zA-Z]+|\w+/).map {|piece|
      piece[/^\d+$/] ? piece.to_i : piece
    }
    @operator = '==' if @operator.nil? || @operator == '='
  end
end

Instance Attribute Details

- (Object) operator (readonly)

Returns the value of attribute operator



8
9
10
# File 'lib/babushka/version_str.rb', line 8

def operator
  @operator
end

- (Object) pieces (readonly)

Returns the value of attribute pieces



8
9
10
# File 'lib/babushka/version_str.rb', line 8

def pieces
  @pieces
end

- (Object) version (readonly)

Returns the value of attribute version



8
9
10
# File 'lib/babushka/version_str.rb', line 8

def version
  @version
end

Instance Method Details

- (Object) <=>(other)



11
12
13
14
15
16
17
18
# File 'lib/babushka/version_str.rb', line 11

def <=> other
  other = other.to_version unless other.is_a? VersionStr
  max_length = [pieces.length, other.pieces.length].max
  (0...max_length).to_a.pick {|index|
    result = compare_pieces pieces[index], other.pieces[index]
    result unless result == 0
  } || 0
end

- (Object) to_s



35
36
37
# File 'lib/babushka/version_str.rb', line 35

def to_s
  @operator == '==' ? @version : "#{@operator} #{@version}"
end