Class: Jsonity::Builder

Inherits:
BasicObject
Defined in:
lib/jsonity/builder.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, content) ⇒ Builder

Initializer



35
36
37
38
# File 'lib/jsonity/builder.rb', line 35

def initialize(object, content)
  @object, @content = object, content
  @deferred_array_blocks = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (private)

Handle ghost methods



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/jsonity/builder.rb', line 102

def method_missing(name, *args, &block)
  name = name.to_s
  is_object = name.match OBJECT_SUFFIX
  name, is_object = name[0..-2], is_object[0] if is_object

  options = args.last.is_a?(::Hash) ? args.pop.dup : {}
  options[:_object] = args[0]
  options[:_nullable] = ('?' == is_object)

  if @array
    @array = false

    if is_object
      array name, options, &block
    else
      ::Kernel.raise UnexpectedNodeOnArrayError.new("Unexpected attribute node `#{name}`")
    end
  else
    if is_object
      hash name, options, &block
    else
      attribute name, options, &block
    end
  end

  self
end

Class Method Details

.build(object = nil, content = nil, &block) ⇒ Hash<String, Object>

Build Jsonity

Returns:

  • (Hash<String, Object>)
    • json object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/jsonity/builder.rb', line 13

def self.build(object = nil, content = nil, &block)
  content = {} unless content.is_a?(::Hash)
  builder = new object, content

  if object.respond_to? :json_attributes
    object.json_attributes.each { |a| builder.__send__(:attribute, a, {}) }
  end

  if object.respond_to? :json_attribute_blocks
    object.json_attribute_blocks.each { |b| builder.(&b) }
  end

  builder.(&block)
  builder._content
end

Instance Method Details

#<=(obj) ⇒ Object

Set ‘obj` for the object

Returns:



45
46
47
# File 'lib/jsonity/builder.rb', line 45

def <=(obj)
  @object = obj
end

#[]Jsonity::Builder

Create array context

Returns:



63
64
65
66
# File 'lib/jsonity/builder.rb', line 63

def []
  @array = true
  self
end

#_contentHash<Object, Object> | nil

Getter for ‘@content`

Returns:



87
88
89
90
# File 'lib/jsonity/builder.rb', line 87

def _content
  evaluate_array_blocks!
  @content
end

#call(obj = nil, &block) ⇒ Object

Mixin / Scoping



74
75
76
77
78
79
80
# File 'lib/jsonity/builder.rb', line 74

def call(obj = nil, &block)
  if obj
    Builder.build obj, @content, &block
  else
    block_call block, self
  end
end

#getObject

Get the object

Returns:



54
55
56
# File 'lib/jsonity/builder.rb', line 54

def get
  @object
end