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



33
34
35
# File 'lib/jsonity/builder.rb', line 33

def initialize(object, content)
  @object, @content = object, content
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Handle ghost methods



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/jsonity/builder.rb', line 74

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

  options = args.last.is_a?(::Hash) ? args.pop : {}
  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

Build Jsonity

Returns:

  • (Hash)
    • json object



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

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, nil }
  end

  builder.(&block)
  builder.__send__ :content
end

Instance Method Details

#<=(obj) ⇒ Object

Set ‘obj` for the object



40
41
42
# File 'lib/jsonity/builder.rb', line 40

def <=(obj)
  @object = obj
end

#[]Jsonity::Builder

Make array context

Returns:



49
50
51
52
# File 'lib/jsonity/builder.rb', line 49

def []
  @array = true
  self
end

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

Mixin / Scoping



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

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