Class: Toml::Merge::KeySorter

Inherits:
Object
  • Object
show all
Defined in:
lib/toml/merge/key_sorter.rb

Overview

Sorts key=value pairs alphabetically within gap-separated blocks
in merged TOML output. Comments are treated as “leading” — owned
by the key that follows them.

Blank lines act as block separators. Sorting is applied independently
within each contiguous block of key=value pairs (and their leading comments).

Table/array-of-tables headers are structural boundaries that start new blocks.

Examples:

sorter = KeySorter.new(result_lines)
sorter.sort!

Constant Summary collapse

KEY_VALUE_RE =

Pattern matching a TOML key=value pair line

/\A\s*([^\[#\s][^\s=]*)\s*=/
TABLE_HEADER_RE =

Pattern matching a table header [name] or [[name]]

/\A\s*\[{1,2}[^\]]+\]{1,2}/
COMMENT_RE =

Pattern matching a comment line

/\A\s*#/

Instance Method Summary collapse

Constructor Details

#initialize(lines) ⇒ KeySorter

Returns a new instance of KeySorter.

Parameters:

  • lines (Array<Hash>)

    MergeResult line hashes with :content key



28
29
30
# File 'lib/toml/merge/key_sorter.rb', line 28

def initialize(lines)
  @lines = lines
end

Instance Method Details

#sort!Array<Hash>

Sort key=value pairs alphabetically within gap-separated blocks.
Modifies @lines in place.

Returns:

  • (Array<Hash>)

    The sorted lines



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/toml/merge/key_sorter.rb', line 36

def sort!
  blocks = partition_into_blocks
  sorted_lines = []

  blocks.each do |block|
    if block[:sortable]
      sorted_lines.concat(sort_block(block[:entries]))
    else
      sorted_lines.concat(block[:lines])
    end
  end

  @lines.replace(sorted_lines)
end