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

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

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


18
19
20
# File 'app/api/core/io/json/stream.rb', line 18

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

Instance Method Details

#array(attribute, objects) ⇒ Object


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

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

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


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

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

#block(attribute, &block) ⇒ Object


42
43
44
# File 'app/api/core/io/json/stream.rb', line 42

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

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


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/api/core/io/json/stream.rb', line 46

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

#named(attribute) ⇒ Object


77
78
79
80
81
82
83
84
# File 'app/api/core/io/json/stream.rb', line 77

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

#openObject


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

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