/Users/jwebb/src/bigjason/elster/lib/elster/streamer.rb in elster-0.0.7 vs /Users/jwebb/src/bigjason/elster/lib/elster/streamer.rb in elster-0.0.8
- old
+ new
@@ -24,25 +24,25 @@
# 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!")
+ # json.key(:mistake, "HUGE!")
#
- # { "mistake" : "HUGE!" }
+ # { "mistake" : "HUGE!" }
#
#
- # json.key(:mistake) do
- # json.key(:type, "HUGE!")
- # end
+ # json.key(:mistake) do
+ # json.key(:type, "HUGE!")
+ # end
#
- # { "mistake" : { "type" : "HUGE!" } }
+ # { "mistake" : { "type" : "HUGE!" } }
#
#
- # json.key(:mistake) do
- # json.add("HUGE!")
- # end
+ # json.key(:mistake) do
+ # json.add("HUGE!")
+ # end
#
# { "mistake" : [ "HUGE!" ] }
def key(key, value=nil, &block)
if @current_type == :array
raise JsonContainerTypeError, "Attempted to write an object `key` value inside a JSON array."
@@ -57,18 +57,15 @@
write encode_value(key)
write ":"
if block
- nest_in
- block.call
- nest_out
+ call_block(block)
else
write encode_value(value)
+ @item_count += 1
end
-
- @item_count += 1
end
# Output an array. If a block is passes the `value` will be ignored and a nested value
# started.
#
@@ -96,18 +93,15 @@
@current_type = :array
begin_section
end
if block
- nest_in
- block.call
- nest_out
+ call_block(block)
else
write encode_value(value)
+ @item_count += 1
end
-
- @item_count += 1
end
protected
def write(output)
@@ -184,9 +178,26 @@
case @current_type
when :array
write("]")
else
write("}")
+ end
+ end
+
+ def call_block(block)
+ nest_in
+ begin
+ block.call
+ rescue
+ raise
+ ensure
+ if @item_count == 0
+ write encode_value(nil)
+ @item_count += 1
+ else
+ nest_out
+ @item_count += 1
+ end
end
end
end
end