Class: Lazy::PP::JSON

Inherits:
String
  • Object
show all
Defined in:
lib/lazy/pp/json.rb,
lib/lazy/pp/json/version.rb

Constant Summary collapse

INDENT_SIZE =
2
INDENT =
' ' * INDENT_SIZE
MAX_CHARACTER_SIZE =
60
VERSION =
"0.0.5"

Instance Method Summary collapse

Constructor Details

#initialize(raw, indent_count = nil) ⇒ JSON

Returns a new instance of JSON.



13
14
15
16
17
18
19
# File 'lib/lazy/pp/json.rb', line 13

def initialize(raw, indent_count=nil)
  super(raw)
  @indent_count = indent_count || 1
  @newline_separator = false
  @key_max_length = 0
  @pretty_print = nil
end

Instance Method Details

#pretty_print(pretty_print) ⇒ Object



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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/lazy/pp/json.rb', line 21

def pretty_print(pretty_print)
  @pretty_print = pretty_print
  begin
    object = ::JSON.parse(self)
  rescue
    if self.kind_of?(Numeric) or self.kind_of?(String)
      @pretty_print.text self
      return
    else
      raise
    end
  end

  if object.empty?
    @pretty_print.pp object
    return
  end

  case object
  when Hash
    @pretty_print.group(indent_width, "{", "}") do
      first = true
      @key_max_length = object.keys.map(&:length).max
      object.each do |key, value|
        @pretty_print.text(",") unless first

        text_indent

        text_key(key)

        first = false

        text_value(value)
      end

      text_prev_indent
    end

  when Array
    @pretty_print.group(indent_width, "[", "]") do
      if separate_elements_with_newline?(object)
        @newline_separator = true
      end

      object.each.with_index do |element, i|
        if i.zero?
          text_indent if @newline_separator
        end

        text_element(element)
        text_separator if i < object.length-1
      end

      text_prev_indent if @newline_separator
    end
  end
end

#pretty_print_cycle(pretty_print) ⇒ Object



79
80
81
# File 'lib/lazy/pp/json.rb', line 79

def pretty_print_cycle(pretty_print)
  pretty_print.text(empty? ? "" : "{...}")
end