Class: Semverve::Formats::ModuleConstants

Inherits:
Object
  • Object
show all
Defined in:
lib/semverve/formats/module_constants.rb

Overview

Handles version files with MAJOR, MINOR, and PATCH constants.

Constant Summary collapse

CONSTANTS =

Mapping of semantic-version parts to Ruby constant names.

Returns:

  • (Hash<Symbol, String>)
{
  major: "MAJOR",
  minor: "MINOR",
  patch: "PATCH"
}.freeze

Instance Method Summary collapse

Instance Method Details

#generate(version, module_name:) ⇒ String

Generates a module-constant version file.

Parameters:

Returns:

  • (String)


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/semverve/formats/module_constants.rb', line 64

def generate(version, module_name:)
  <<~RUBY
    # frozen_string_literal: true

    ##
    # Namespace for #{module_name}.
    module #{module_name}
      ##
      # Semantic version information for #{module_name}.
      module Version
        ##
        # Major version.
        #
        # @return [Integer]
        MAJOR = #{version.major}

        ##
        # Minor version.
        #
        # @return [Integer]
        MINOR = #{version.minor}

        ##
        # Patch version.
        #
        # @return [Integer]
        PATCH = #{version.patch}

        module_function

        ##
        # Version as +[MAJOR, MINOR, PATCH]+
        #
        # @return [Array<Integer>]
        def to_a
          [MAJOR, MINOR, PATCH]
        end

        ##
        # Version as +MAJOR.MINOR.PATCH+
        #
        # @return [String]
        def to_s
          to_a.join(".")
        end
      end

      ##
      # Full gem version string.
      #
      # @return [String]
      VERSION = #{module_name}::Version.to_s
    end
  RUBY
end

#parse(content, path:) ⇒ Semverve::SemanticVersion

Parses a semantic version from module-constant content.

Parameters:

  • content (String)
  • path (String)

Returns:



28
29
30
31
32
33
34
# File 'lib/semverve/formats/module_constants.rb', line 28

def parse(content, path:)
  SemanticVersion.new(
    major: constant_value(content, path, :major),
    minor: constant_value(content, path, :minor),
    patch: constant_value(content, path, :patch)
  )
end

#replace(content, version, path:) ⇒ String

Replaces MAJOR, MINOR, and PATCH values in module-constant content.

Parameters:

Returns:

  • (String)


44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/semverve/formats/module_constants.rb', line 44

def replace(content, version, path:)
  CONSTANTS.reduce(content) do |updated, (part, constant)|
    pattern = /^(\s*#{constant}\s*=\s*)\d+/
    value = version.public_send(part)

    unless updated.match?(pattern)
      raise Error, "Could not find #{constant} in #{path}."
    end

    updated.sub(pattern) { "#{$1}#{value}" }
  end
end