Class: ForemanInventoryUpload::Generators::JsonStream

Inherits:
Object
  • Object
show all
Defined in:
lib/foreman_inventory_upload/generators/json_stream.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(out) ⇒ JsonStream

Returns a new instance of JsonStream.



6
7
8
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 6

def initialize(out)
  @out = out
end

Instance Attribute Details

#outObject (readonly)

Returns the value of attribute out.



4
5
6
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 4

def out
  @out
end

Instance Method Details

#arrayObject



10
11
12
13
14
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 10

def array
  @out << '['
  yield
  @out << ']'
end

#array_field(name, last = false, &block) ⇒ Object



39
40
41
42
43
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 39

def array_field(name, last = false, &block)
  @out << "\"#{name}\": "
  array(&block)
  @out << ',' unless last
end

#commaObject



22
23
24
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 22

def comma
  @out << ', '
end

#objectObject



16
17
18
19
20
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 16

def object
  @out << '{'
  yield
  @out << '}'
end

#object_field(name, last = false, &block) ⇒ Object



55
56
57
58
59
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 55

def object_field(name, last = false, &block)
  @out << "\"#{name}\": "
  object(&block)
  @out << ',' unless last
end

#raw(string) ⇒ Object



26
27
28
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 26

def raw(string)
  @out << string
end

#simple_field(name, value, last = false, &block) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 30

def simple_field(name, value, last = false, &block)
  return if value.nil? || value.try(:empty?)
  return if value.kind_of?(Array) && value.compact.empty?

  block ||= ->(value) { value }

  @out << "\"#{name}\": #{stringify_value(block.call(value))}#{last ? '' : ','}"
end

#string_array_value(name, value, last = false) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 45

def string_array_value(name, value, last = false)
  return if value.empty?

  string_value = value.map { |v| stringify_value(v) }

  array_field(name, last) do
    raw(string_value.join(', '))
  end
end

#stringify_value(value) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/foreman_inventory_upload/generators/json_stream.rb', line 61

def stringify_value(value)
  return value if value.is_a?(Integer)
  return value if value.is_a?(TrueClass)
  return value if value.is_a?(FalseClass)
  return value.to_json if value.is_a?(Hash)

  ActiveSupport::JSON.encode(value)
end