Class: EasyJSONMatcher::Printer

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_json_matcher/printer.rb

Overview

Class which is used to convert a node to a human-readable format for inspection purposes.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node:) ⇒ Printer

Returns a new instance of Printer.



10
11
12
# File 'lib/easy_json_matcher/printer.rb', line 10

def initialize(node:)
  @n = node
end

Instance Attribute Details

#nObject (readonly)

Returns the value of attribute n.



8
9
10
# File 'lib/easy_json_matcher/printer.rb', line 8

def n
  @n
end

Instance Method Details

#grow_s(n) ⇒ Object



49
50
51
52
53
# File 'lib/easy_json_matcher/printer.rb', line 49

def grow_s(n)
  buffer = ""
  n.times { buffer << " " }
  buffer
end

#inspectObject



14
15
16
17
# File 'lib/easy_json_matcher/printer.rb', line 14

def inspect
  root_flag = "root: "
  root_flag + pretty_print(n.validation_chain, root_flag.length)
end

#pretty_print(node, n) ⇒ Object



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
# File 'lib/easy_json_matcher/printer.rb', line 19

def pretty_print(node, n)
  depth = grow_s(n)
  d = n + 1
  case node
  when Node
    pretty_print node.node_validator, n
  when Validator
    pretty_print node.validation_chain, n
  when ArrayValidator
    pretty_print node.verifier, n
  when ArrayContentValidator
    pretty_print node.verifier, n
  when ValidationRule
    node.type.to_s
  when ValidationStep
    head = pretty_print node.verifier, d
    tail = pretty_print node.next_step, n unless node.is_tail?
    tail_string = tail ? "\n#{depth}#{tail}" : ""
    "#{head} | #{tail_string}"
  when ValidatorSet
    parts = node.validators.each_with_object([]) do |k_v, out|
      key_padding = d + k_v[0].length + 1
      out << "#{k_v[0]}: #{pretty_print k_v[1], key_padding}\n"
    end
    parts.join(depth)
  else
    throw Error.new(node.class.to_s)
  end
end