genki (owner)

Revisions

gist: 112140 Download_button fork
public
Public Clone URL: git://gist.github.com/112140.git
Embed All Files: show embed
haml_formatter.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/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