Skip to content

Instantly share code, notes, and snippets.

@roktas
Created May 3, 2019 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roktas/5764ee0fc8c5c4b374ca1601686919e4 to your computer and use it in GitHub Desktop.
Save roktas/5764ee0fc8c5c4b374ca1601686919e4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: true
class Aligner
LINE = /
(?:^|\A) # beginning of line
(?<lhs>\s*[^#:]+:) # lhs
(?:\s*) # optional space
(?<rhs>\S.*) # rhs
(?:$|\z) # end of line
/x.freeze
def self.call(*args)
new(*args).()
end
def initialize(content, npad = nil)
@lines = content.split "\n"
@npad = npad || 1
@longest_length = calculate_longest_length
end
def call
lines.map do |line|
next line unless (m = line.match(LINE))
pad = ' ' * (longest_length - m[:lhs].length)
m[:lhs] + pad + m[:rhs]
end.join("\n") + "\n"
end
private
attr_reader :lines, :npad, :longest_length
def calculate_longest_length
lines.map do |line|
next 0 unless (m = line.match(LINE))
(m[:lhs] || '').length
end.max + npad
end
end
def main
puts Aligner.(ARGF.read)
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment