Module: Papercraft::JSON

Included in:
JSONRenderer
Defined in:
lib/papercraft/json.rb

Overview

JSON renderer extensions

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, value = nil, &block) ⇒ void

This method returns an undefined value.

Intercepts method calls by adding key-value pairs to the current object target.

Parameters:

  • key (Symbol)

    key

  • value (Object) (defaults to: nil)

    value



56
57
58
# File 'lib/papercraft/json.rb', line 56

def method_missing(key, value = nil, &block)
  kv(key, value, &block)
end

Instance Method Details

#initialize(&template) ⇒ Object

Initializes a JSON renderer, setting up an object stack.



9
10
11
12
# File 'lib/papercraft/json.rb', line 9

def initialize(&template)
  @object_stack = [nil]
  super
end

#item(value = nil, _for: nil, &block) ⇒ void

This method returns an undefined value.

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.

Papercraft.json {
  item 'foo'
  item 'bar'
}.render #=> "[\"foo\", \"bar\"]"

Parameters:

  • value (Object) (defaults to: nil)

    item



25
26
27
28
29
30
31
32
33
# File 'lib/papercraft/json.rb', line 25

def item(value = nil, _for: nil, &block)
  return _for.each { |*a| item(value) { block.(*a)} } if _for

  verify_array_target
  if block
    value = enter_object(&block)
  end
  push_array_item(value)
end

#kv(key, value = nil, &block) ⇒ void

This method returns an undefined value.

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.

Parameters:

  • key (Object)

    key

  • value (Object) (defaults to: nil)

    value



42
43
44
45
46
47
48
# File 'lib/papercraft/json.rb', line 42

def kv(key, value = nil, &block)
  verify_hash_target
  if block
    value = enter_object(&block)
  end
  push_kv_item(key, value)
end

#to_sString

Converts the root object target to JSON.

Returns:

  • (String)

    JSON template result



63
64
65
# File 'lib/papercraft/json.rb', line 63

def to_s
  @object_stack[0].to_json
end