module Papercraft::JSON
JSON
renderer extensions
Public Class Methods
Initializes a JSON
renderer, setting up an object stack.
# File lib/papercraft/json.rb, line 9 def initialize(&template) @object_stack = [nil] super end
Public Instance Methods
Adds an array item to the current object target. If a block is given, the block is evaulated against a new object target, then added to the current array.
@param value [Object] item @param &block [Proc] template block @return [void]
# File lib/papercraft/json.rb, line 21 def item(value = nil, &block) verify_array_target if block value = enter_object(&block) end push_array_item(value) end
Adds a key-value item to the current object target. If a block is given, the block is evaulated against a new object target, then used as the value.
@param key [Object] key @param value [Object] value @param &block [Proc] template block @return [void]
# File lib/papercraft/json.rb, line 37 def kv(key, value = nil, &block) verify_hash_target if block value = enter_object(&block) end push_kv_item(key, value) end
Intercepts method calls by adding key-value pairs to the current object target.
@param key [Object] key @param value [Object] value @param &block [Proc] template block @return [void]
# File lib/papercraft/json.rb, line 52 def method_missing(sym, value = nil, &block) kv(sym, value, &block) end
Private Instance Methods
Adds a new object to the object stack, evaluates the given template block, then pops the object off the stack.
@param &block [Proc] template block @return [void]
# File lib/papercraft/json.rb, line 120 def enter_object(&block) @object_stack << nil instance_eval(&block) @object_stack.pop end
Pushes an array item to the current object target.
@param value [Object] item @return [void]
# File lib/papercraft/json.rb, line 102 def push_array_item(value) @object_stack[-1] << value end
Pushes a key value into the current object target.
@param key [Object] key @param value [Object] value @return [void]
# File lib/papercraft/json.rb, line 111 def push_kv_item(key, value) @object_stack[-1][key] = value end
Verifies that the current object target is not a hash.
@return [bool]
# File lib/papercraft/json.rb, line 77 def verify_array_target case @object_stack[-1] when nil @object_stack[-1] = [] when Hash raise "Mixing array and hash values" end end
Verifies that the current object target is not an array.
@return [bool]
# File lib/papercraft/json.rb, line 89 def verify_hash_target case @object_stack[-1] when nil @object_stack[-1] = {} when Array raise "Mixing array and hash values" end end
Adds a new entry to the object stack and evaluates the given block.
@param &block [Proc] template block @return [void]
# File lib/papercraft/json.rb, line 69 def with_object(&block) @object_stack << nil instance_eval(&block) end