Class: Elster::Streamer

Inherits:
Object
  • Object
show all
Defined in:
lib/elster/streamer.rb

Constant Summary

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Streamer) initialize(output)

Create a new instance of Streamer with the specified output stream. The output must respond to write.



9
10
11
12
13
14
# File 'lib/elster/streamer.rb', line 9

def initialize(output)
  @output = output
  # Some mutable state to make Rich Hickey weep.
  @stack = []
  @item_count = 0
end

Instance Attribute Details

- (Object) output (readonly)

Returns the value of attribute output



5
6
7
# File 'lib/elster/streamer.rb', line 5

def output
  @output
end

Instance Method Details

- (Object) add(value = nil, &block)

Output an array. If a block is passes the value will be ignored and a nested value started.

Example:

json.add(1) json.add("Ansible")

[ 1, "Ansible" ]

json.add(1) json.add do json.set(:name, "Wiggens") end

[ 1, { "name" : "Wiggens" } ]



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/elster/streamer.rb', line 88

def add(value=nil, &block)
  if @current_type == :object
    raise JsonContainerTypeError, "Attempted to add an array value inside a JSON object."
  end

  if @item_count > 0
    write ","
  else
    @current_type = :array
    begin_section
  end

  if block
    nest_in
    block.call
    nest_out
  else
    write encode_value(value)
  end

  @item_count += 1
end

- (Object) close(close_stream = false)

Close the encoding optionally closing the provided output stream.



17
18
19
20
21
22
# File 'lib/elster/streamer.rb', line 17

def close(close_stream=false)
  end_section
  if close_stream
    @output.close
  end
end

- (Object) key(key, value = nil, &block)

Output an object key value pair. If a block is passed, the value will be ignored and a nested object or array can be added.

Example:

json.key(:mistake, "HUGE!")

{ "mistake" : "HUGE!" }

json.key(:mistake) do json.key(:type, "HUGE!") end

{ "mistake" : { "type" : "HUGE!" } }

json.key(:mistake) do json.add("HUGE!") end

{ "mistake" : [ "HUGE!" ] }



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
# File 'lib/elster/streamer.rb', line 46

def key(key, value=nil, &block)
  if @current_type == :array
    raise JsonContainerTypeError, "Attempted to write an object `key` value inside a JSON array."
  end

  if @item_count > 0
    write ","
  else
    @current_type = :object
    begin_section
  end

  write encode_value(key)
  write ":"

  if block
    nest_in
    block.call
    nest_out
  else
    write encode_value(value)
  end

  @item_count += 1
end