Class: Core::Io::Json::Stream

Inherits:
Object
  • Object
show all
Defined in:
app/api/core/io/json/stream.rb

Overview

Custom JSON streaming class to handle streamed serialization of API V1 objects

Defined Under Namespace

Classes: Interface

Constant Summary collapse

ZIPPABLE =
Interface.new(:zip).freeze

Instance Method Summary collapse

Constructor Details

#initialize(buffer) ⇒ Stream

Returns a new instance of Stream.


20
21
22
# File 'app/api/core/io/json/stream.rb', line 20

def initialize(buffer)
  @buffer, @have_output_value = buffer, []
end

Instance Method Details

#array(attribute, objects) ⇒ Object


32
33
34
# File 'app/api/core/io/json/stream.rb', line 32

def array(attribute, objects)
  named(attribute) { array_encode(objects) { |v| yield(self, v) } }
end

#attribute(attribute, value, options = {}) ⇒ Object


36
37
38
# File 'app/api/core/io/json/stream.rb', line 36

def attribute(attribute, value, options = {})
  named(attribute) { encode(value, options) }
end

#block(attribute, &block) ⇒ Object


40
41
42
# File 'app/api/core/io/json/stream.rb', line 40

def block(attribute, &block)
  named(attribute) { open(&block) }
end

#encode(object, options = {}) ⇒ Object

rubocop:todo Metrics/MethodLength, Metrics/AbcSize


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
# File 'app/api/core/io/json/stream.rb', line 45

def encode(object, options = {}) # rubocop:todo Metrics/CyclomaticComplexity
  case object
  when NilClass
    unencoded('null')
  when Symbol
    string_encode(object)
  when TrueClass
    unencoded('true')
  when FalseClass
    unencoded('false')
  when String
    string_encode(object)
  when Integer
    unencoded(object.to_s)
  when Float
    unencoded(object.to_s)
  when Date
    string_encode(object)
  when ActiveSupport::TimeWithZone
    string_encode(object.to_s)
  when Time
    string_encode(object.to_s(:compatible))
  when Hash
    hash_encode(object, options)
  when ZIPPABLE
    array_encode(object) { |o| encode(o, options) }
  else
    object_encode(object, options)
  end
end

#named(attribute) ⇒ Object


88
89
90
91
92
93
94
95
# File 'app/api/core/io/json/stream.rb', line 88

def named(attribute)
  unencoded(',') if have_output_value?
  encode(attribute)
  unencoded(':')
  yield
ensure
  have_output_value
end

#openObject


24
25
26
27
28
29
30
# File 'app/api/core/io/json/stream.rb', line 24

def open
  flush do
    unencoded('{')
    yield(self)
    unencoded('}')
  end
end