Sha256: 54795917ff3c857c52a6a6eb890c859b91c47f4ad136f7b00eb4fe97310591d8

Contents?: true

Size: 1.65 KB

Versions: 6

Compression:

Stored size: 1.65 KB

Contents

# frozen_string_literal: true

require "refinements/structs"

module Versionaire
  # An immutable, semantic version value object.
  Version = Struct.new :major, :minor, :patch, keyword_init: true do
    include Comparable

    using Refinements::Structs

    def self.delimiter = "."

    def self.pattern
      /
        \A(                  # Start of string and OR.
        \d*                  # Major only.
        |                    # OR pipe.
        \d+                  # Major.
        #{delimiter}?        # Delimiter.
        \d*                  # Minor.
        (?:#{delimiter}\d+)  # Passive delimiter and patch.
        )\z                  # End of OR and string.
      /x
    end

    def initialize major: 0, minor: 0, patch: 0
      super
      validate
      freeze
    end

    def []= key, value
      super(key, value).tap { validate }
    end

    def + other
      revalue(other.to_h) { |previous, current| previous + current }
    end

    def - other
      revalue(other.to_h) { |previous, current| previous - current }
    end

    def == other
      hash == other.hash
    end

    alias_method :eql?, :==

    def <=> other
      to_s <=> other.to_s
    end

    def down(key, value = 1) = revalue(key => value) { |previous, current| previous - current }

    def up(key, value = 1) = revalue(key => value) { |previous, current| previous + current }

    def to_s = to_a.join(self.class.delimiter)

    alias_method :to_str, :to_s
    alias_method :values, :to_a

    private

    def validate
      fail Errors::InvalidNumber if to_a.any? { |number| !number.is_a? Integer }
      fail Errors::NegativeNumber if to_a.any?(&:negative?)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
versionaire-9.4.0 lib/versionaire/version.rb
versionaire-9.3.0 lib/versionaire/version.rb
versionaire-9.2.2 lib/versionaire/version.rb
versionaire-9.2.1 lib/versionaire/version.rb
versionaire-9.2.0 lib/versionaire/version.rb
versionaire-9.1.1 lib/versionaire/version.rb