-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat_hash.rb
executable file
·60 lines (53 loc) · 979 Bytes
/
format_hash.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
53
54
55
56
57
58
59
60
#!/usr/bin/env ruby
# Formats ruby hashes and assignments
# a => 1
# ab => 2
# abc => 3
#
# becomes
# a => 1
# ab => 2
# abc => 3
#
# a = 1
# ab = 2
# abc = 3
#
# becomes
# a = 1
# ab = 2
# abc = 3
#
# a: 1
# ab: 2
# abc: 3
#
# becomes
# a: 1
# ab: 2
# abc: 3
#
# From github.com/xaviershay/dotfiles
OPERATOR_RE = /:(?=\s)|=>|=/
lines = readlines
operator = nil
indent = lines.first.index(/[^\s]/)
# Massage into an array of [key, value]
lines.collect! do |line|
if line =~ OPERATOR_RE
operator ||= $&
line.partition(operator).map(&:strip)
end
end
max_key_length = lines.map {|line| line[0].length}.max
# Pad each key with whitespace to match length of longest key
lines.map! do |line|
if operator =~ /:/
line[0] = "%#{indent}s%-#{max_key_length+2}s" % ["", line[0] + ': ']
line[0] + line[2]
else
line[0] = "%#{indent}s%-#{max_key_length}s" % ["", line[0]]
line[0] + " #{operator} " + line[2]
end
end
print lines.join("\n")