Created
May 3, 2019 19:33
-
-
Save roktas/5764ee0fc8c5c4b374ca1601686919e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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