Sha256: f5ca7644c86e836754cc0e65ea6e2b7b560abde35d7b1028701b3d70475f71f9

Contents?: true

Size: 1.51 KB

Versions: 12

Compression:

Stored size: 1.51 KB

Contents

# frozen_string_literal: true

class Version
  InvalidVersion = Class.new(ArgumentError)
  InvalidRequire = Class.new(ArgumentError)

  MSGS = {
    version: 'Unable to parse version: %p',
    require: 'Unable to parse requirement: %p'
  }.freeze

  VERSION = /^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/
  REQUIRE = /^(~>|>|>=|=|!=|<=|<) (\d+(?:\.\d+)?(?:\.\d+)?)$/

  include Comparable

  def initialize(str)
    @nums = split(str) || raise(InvalidVersion, MSGS[:version] % str)
  end

  def satisfies?(str)
    send(*parse(str) || raise(InvalidRequire, MSGS[:require] % str))
  end

  def size
    nums.size
  end

  def to_a
    nums
  end

  def to_s
    nums.join('.')
  end

  def ==(other)
    trunc(other.size).to_a == other.to_a
  end

  def !=(other)
    trunc(other.size).to_a != other.to_a
  end

  def <=>(other)
    to_a <=> other.to_a
  end

  define_method :'~>' do |min|
    min = min.trunc(nums.size)
    max = min.clone.bump
    self >= min && self < max
  end

  def bump
    ix = nums[1] ? -2 : -1
    nums[ix] = nums[ix] + 1
    nums[-1] = nums[-1] = 0 if nums[1]
    self
  end

  def trunc(size)
    @nums = nums[0..size - 1]
    self
  end

  def clone
    Version.new(to_s)
  end

  private

  attr_reader :nums

  def split(str)
    str =~ VERSION && [::Regexp.last_match(1), ::Regexp.last_match(2), ::Regexp.last_match(3)].compact.map(&:to_i)
  end

  def parse(str)
    op, version = str =~ REQUIRE && [::Regexp.last_match(1), ::Regexp.last_match(2)]
    op = '==' if op == '='
    [op, Version.new(version)] if op
  end
end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
dpl-2.0.5.3 lib/dpl/support/version.rb
dpl-2.0.5.3.beta.1 lib/dpl/support/version.rb
dpl-2.0.5.2 lib/dpl/support/version.rb
dpl-2.0.5.2.beta.1 lib/dpl/support/version.rb
dpl-2.0.5.1 lib/dpl/support/version.rb
dpl-2.0.5.beta.2.1 lib/dpl/support/version.rb
dpl-2.0.5.beta.2 lib/dpl/support/version.rb
dpl-2.0.5 lib/dpl/support/version.rb
dpl-2.0.5.beta.1 lib/dpl/support/version.rb
dpl-2.0.5.beta lib/dpl/support/version.rb
travis_dpl_test-2.0.3.beta.4.ror.1 lib/dpl/support/version.rb
travis_dpl_test-2.0.3.beta.4.ror lib/dpl/support/version.rb