Module: Chronicle::Models::Builder

Included in:
Chronicle::Models
Defined in:
lib/chronicle/models/builder.rb

Overview

Utility methods to build models from hash input

Instance Method Summary collapse

Instance Method Details

#build(obj) ⇒ Object

Build a nested a model with nested associated from a hash in json-ld format

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/chronicle/models/builder.rb', line 6

def build(obj)
  raise ArgumentError, 'Object must be a hash' unless obj.is_a?(Hash)

  type = obj[:@type]
  raise ArgumentError, 'Object must have a type' unless type

  model_klass = const_get(type.to_sym)
  raise ArgumentError, "Unknown model type: #{type}" unless model_klass

  # recursively create nested models
  # TODO: have a better way of detecting chronicle schema objects
  begin
    obj.each do |property, value|
      if value.is_a?(Hash)
        obj[property] = build(value)
      elsif value.is_a?(Array)
        obj[property] = value.map do |v|
          v.is_a?(Hash) ? build(v) : v
        end
      end
    end

    model_klass.new(obj.except(:@type))
  rescue Chronicle::Models::AttributeError => e
    raise ArgumentError, e.message
  end
end