Created
May 15, 2009 09:28
-
-
Save genki/112140 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 | |
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