Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env ruby
class Formatter
WIDTH = 78
def initialize(string)
@string = string.gsub(/\s*\|$/, '')
end
def format
result = fetch WIDTH
indent = indent_of(result)
lines = []
lines << fetch(WIDTH - indent - 2, true) until @string.chomp.empty?
indent_space = " "*(indent + 2)
result = with_bar(result, WIDTH)
lines.each do |line|
result << with_bar(indent_space + line, WIDTH)
end
result
end
private
def slice(string, length)
result = ""
string.split(//u).each do |char|
length -= char.length == 1 ? 1 : 2
break if length < 0
result << char
break if char.chomp.empty?
end
result
end
def fetch(length, ignore_indent = false)
@string.sub!(/^\s*/, '') if ignore_indent
result = slice(@string, length)
@string = @string[result.length..-1]
result.chomp
end
def indent_of(string)
string.index(/\S/)
end
def with_bar(string, right)
slice((string + " " * WIDTH), right) + " |\n"
end
end
puts Formatter.new(STDIN.read).format
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.