Class: Elster::Streamer
- Inherits:
-
Object
- Object
- Elster::Streamer
- Defined in:
- lib/elster/streamer.rb
Instance Attribute Summary collapse
-
#output ⇒ Object
readonly
Returns the value of attribute output.
Instance Method Summary collapse
-
#add(value = nil, &block) ⇒ Object
Output an array.
-
#close(close_stream = false) ⇒ Object
Close the encoding optionally closing the provided output stream.
-
#initialize(output) ⇒ Streamer
constructor
Create a new instance of Streamer with the specified output stream.
-
#key(key, value = nil, &block) ⇒ Object
Output an object key value pair.
Constructor Details
#initialize(output) ⇒ Streamer
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
#output ⇒ Object (readonly)
Returns the value of attribute output.
5 6 7 |
# File 'lib/elster/streamer.rb', line 5 def output @output end |
Instance Method Details
#add(value = nil, &block) ⇒ Object
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" } ]
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/elster/streamer.rb', line 85 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 call_block(block) else write encode_value(value) @item_count += 1 end end |
#close(close_stream = false) ⇒ Object
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 |
#key(key, value = nil, &block) ⇒ Object
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 |
# 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 call_block(block) else write encode_value(value) @item_count += 1 end end |