Module: BoxCli::HashToPretty

Defined in:
lib/box_cli/hash_to_pretty.rb

Instance Method Summary collapse

Instance Method Details

#to_pretty(indent = 0) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/box_cli/hash_to_pretty.rb', line 7

def to_pretty(indent = 0)
  "".tap do |s|
    indifferent = self.with_indifferent_access
    keys = self.keys.map(&:to_s)
    keys.sort! unless ActiveSupport::OrderedHash === self
    humanized = keys.inject({}) { |m, k| m[k] = k.humanize; m }
    max_length = humanized.values.map(&:length).max
    keys.each do |key|
      s << "".ljust(indent) << (humanized[key] + ': ').ljust(max_length + 2)
      if Hash === indifferent[key]
        s.strip! << "\n"
        hash = indifferent[key]
        hash.extend HashToPretty
        s << hash.to_pretty(indent + 3)
      else
        s << indifferent[key].to_s << "\n"
      end
    end
  end
end