Class: Tokamak::Builder::Json

Inherits:
Base
  • Object
show all
Defined in:
lib/tokamak/builder/json.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

build, builder_for, collection_helper_default_options, generic_helper, global_media_types, helper, media_types, member_helper_default_options

Constructor Details

#initialize(obj, options = {}) ⇒ Json

Returns a new instance of Json.



9
10
11
12
13
14
# File 'lib/tokamak/builder/json.rb', line 9

def initialize(obj, options = {})
  initialize_library
  @raw     = options[:root] ? { options[:root] => {} } : {}
  @current = options[:root] ? @raw[options[:root]]     : @raw
  @obj     = obj
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



7
8
9
# File 'lib/tokamak/builder/json.rb', line 7

def raw
  @raw
end

Instance Method Details

#initialize_libraryObject



16
17
18
19
# File 'lib/tokamak/builder/json.rb', line 16

def initialize_library
  return if defined?(::JSON)
  require "json/pure"
end

#insert_value(name, prefix, *args, &block) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/tokamak/builder/json.rb', line 53

def insert_value(name, prefix, *args, &block)
  node = create_element(block_given?, *args)

  if block_given?
    parent = @current
    @current = node
    block.call
    @current = parent
  end

  add_to(@current, name, node)
end


42
43
44
45
46
47
48
49
50
51
# File 'lib/tokamak/builder/json.rb', line 42

def link(relationship, uri, options = {})
  # Start link array
  @current["link"] = [] unless @current["link"]
  stringify_keys(options) 

  options["rel"]  = relationship.to_s
  options["href"] = uri
  options["type"] ||= "application/json"
  insert_value("link", nil, options)
end

#members(options = {}, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tokamak/builder/json.rb', line 21

def members(options = {}, &block)
  collection = options[:collection] || @obj
  raise Tokamak::BuilderError.new("Members method require a collection to execute") unless collection.respond_to?(:each)
  root = options[:root] || "members"

  add_to(@current, root, [])
  collection.each do |member|

    parent = @current
    @current = {}
    block.call(self, member)
    add_to(parent, root, @current)
    @current = parent

  end
end

#representationObject



66
67
68
# File 'lib/tokamak/builder/json.rb', line 66

def representation
  @raw.to_json
end

#values(options = {}) {|Values.new(self)| ... } ⇒ Object

Yields:



38
39
40
# File 'lib/tokamak/builder/json.rb', line 38

def values(options = {}, &block)
  yield Values.new(self)
end