Class: Hypertemplate::Builder::Json
- Inherits:
-
Base
- Object
- Base
- Hypertemplate::Builder::Json
show all
- Defined in:
- lib/hypertemplate/builder/json.rb
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Methods inherited from Base
build, build_dsl, collection_helper_default_options, copy_internal_variables, #each, generic_helper, helper, member_helper_default_options, #method_missing, #ns, #write
Constructor Details
#initialize(obj, options = {}) ⇒ Json
Returns a new instance of Json.
11
12
13
14
15
16
17
18
19
20
|
# File 'lib/hypertemplate/builder/json.rb', line 11
def initialize(obj, options = {})
initialize_library
if options[:root]
@raw = { options[:root] => {} }
@current = @raw[options[:root]]
else
@current = @raw = {}
end
@obj = obj
end
|
Instance Attribute Details
#raw ⇒ Object
Returns the value of attribute raw.
9
10
11
|
# File 'lib/hypertemplate/builder/json.rb', line 9
def raw
@raw
end
|
Class Method Details
5
6
7
|
# File 'lib/hypertemplate/builder/json.rb', line 5
def self.media_types
["application/json"]
end
|
Instance Method Details
#initialize_library ⇒ Object
22
23
24
25
|
# File 'lib/hypertemplate/builder/json.rb', line 22
def initialize_library
return if defined?(::JSON)
require "json/pure"
end
|
#insert_value(name, prefix, *args, &block) ⇒ Object
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# File 'lib/hypertemplate/builder/json.rb', line 65
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
|
#link(relationship, uri, options = {}) ⇒ Object
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/hypertemplate/builder/json.rb', line 54
def link(relationship, uri, options = {})
@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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# File 'lib/hypertemplate/builder/json.rb', line 27
def members(options = {}, &block)
collection = options[:collection] || @obj
raise Hypertemplate::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 = {}
if block.arity==1
block.call(member)
else
block.call(self, member)
end
add_to(parent, root, @current)
@current = parent
end
end
|
#representation ⇒ Object
79
80
81
|
# File 'lib/hypertemplate/builder/json.rb', line 79
def representation
@raw.to_json
end
|
#values(options = {}) {|Values.new(self)| ... } ⇒ Object
50
51
52
|
# File 'lib/hypertemplate/builder/json.rb', line 50
def values(options = {}, &block)
yield Values.new(self)
end
|