Skip to content

Instantly share code, notes, and snippets.

@genki
Created May 15, 2009 09:28
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 genki/112140 to your computer and use it in GitHub Desktop.
Save genki/112140 to your computer and use it in GitHub Desktop.
#!/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