Class: Jsonit::Builder
- Inherits:
-
Object
show all
- Defined in:
- lib/jsonit/builder.rb
Instance Method Summary
collapse
Constructor Details
#initialize(scope = {}) {|_self| ... } ⇒ Builder
Returns a new instance of Builder.
6
7
8
9
|
# File 'lib/jsonit/builder.rb', line 6
def initialize(scope={})
@document = @current_scope = scope
yield self if block_given?
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args, &blk) ⇒ Object
57
58
59
60
61
62
|
# File 'lib/jsonit/builder.rb', line 57
def method_missing(meth, *args, &blk)
if (meth.to_s =~ /\?$|!$/).nil?
return set!(meth, *args, &blk)
end
super
end
|
Instance Method Details
#array!(key, collection = [], &blk) ⇒ Object
43
44
45
46
|
# File 'lib/jsonit/builder.rb', line 43
def array!(key, collection=[], &blk)
collection.map! { |itm| object!(nil, itm, &blk) } if block_given?
assign!(key, collection)
end
|
#assign!(key, value = nil) ⇒ Object
48
49
50
51
52
53
54
55
|
# File 'lib/jsonit/builder.rb', line 48
def assign!(key, value=nil)
if value.is_a?(Hash) && @current_scope[key].is_a?(Hash)
@current_scope[key].merge!(value)
else
@current_scope[key] = value
end
self
end
|
#encode_json ⇒ Object
Also known as:
as_json
20
21
22
|
# File 'lib/jsonit/builder.rb', line 20
def encode_json(*)
@document
end
|
#object!(key = nil, value = nil) {|value| ... } ⇒ Object
36
37
38
39
40
41
|
# File 'lib/jsonit/builder.rb', line 36
def object!(key=nil, value=nil, &blk)
@current_scope, previous_scope = {}, @current_scope
yield value
@current_scope, new_scope = previous_scope, @current_scope
!key.nil? ? assign!(key, new_scope) : Builder.new(new_scope)
end
|
#set!(key = nil, value = nil, &blk) ⇒ Object
25
26
27
28
29
30
31
32
33
34
|
# File 'lib/jsonit/builder.rb', line 25
def set!(key=nil, value=nil, &blk)
if !block_given?
assign!(key, value)
elsif value.is_a?(Enumerable)
array!(key, value, &blk)
else
object!(key, value, &blk)
end
self
end
|
#to_json(*args) ⇒ Object
15
16
17
|
# File 'lib/jsonit/builder.rb', line 15
def to_json(*args)
@document.to_json(*args)
end
|
#to_s ⇒ Object
11
12
13
|
# File 'lib/jsonit/builder.rb', line 11
def to_s
to_json
end
|