Class: AwesomePrint::Formatters::HashFormatter

Inherits:
BaseFormatter show all
Defined in:
lib/awesome_print/formatters/hash_formatter.rb

Constant Summary

Constants inherited from BaseFormatter

BaseFormatter::DEFAULT_LIMIT_SIZE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseFormatter

#align, #get_limit_size, #indent, #indentation, #indented, #limited, #method_tuple, #outdent, #should_be_limited?

Methods included from Colorize

#colorize

Constructor Details

#initialize(hash, inspector) ⇒ HashFormatter

Returns a new instance of HashFormatter.



9
10
11
12
13
# File 'lib/awesome_print/formatters/hash_formatter.rb', line 9

def initialize(hash, inspector)
  @hash = hash
  @inspector = inspector
  @options = inspector.options
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



7
8
9
# File 'lib/awesome_print/formatters/hash_formatter.rb', line 7

def hash
  @hash
end

#inspectorObject (readonly)

Returns the value of attribute inspector.



7
8
9
# File 'lib/awesome_print/formatters/hash_formatter.rb', line 7

def inspector
  @inspector
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/awesome_print/formatters/hash_formatter.rb', line 7

def options
  @options
end

Instance Method Details

#formatObject



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
# File 'lib/awesome_print/formatters/hash_formatter.rb', line 15

def format
  return "{}" if hash == {}

  keys = hash.keys
  keys = keys.sort { |a, b| a.to_s <=> b.to_s } if options[:sort_keys]
  data = keys.map do |key|
    plain_single_line do
      [ inspector.awesome(key), hash[key] ]
    end
  end

  width = data.map { |key, | key.size }.max || 0
  width += indentation if options[:indent] > 0

  data = data.map do |key, value|
    indented do
      align(key, width) << colorize(" => ", :hash) << inspector.awesome(value)
    end
  end

  data = limited(data, width, :hash => true) if should_be_limited?
  if options[:multiline]
    "{\n" << data.join(",\n") << "\n#{outdent}}"
  else
    "{ #{data.join(', ')} }"
  end
end