Class: Reynard::ObjectBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/reynard/object_builder.rb

Overview

Defines dynamic classes based on schema and instantiates them for a response.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema:, inflector:, parsed_body:, model_name: nil) ⇒ ObjectBuilder

Returns a new instance of ObjectBuilder.



10
11
12
13
14
15
# File 'lib/reynard/object_builder.rb', line 10

def initialize(schema:, inflector:, parsed_body:, model_name: nil)
  @schema = schema
  @inflector = inflector
  @parsed_body = parsed_body
  @model_name = model_name
end

Instance Attribute Details

#parsed_bodyObject (readonly)

Returns the value of attribute parsed_body.



8
9
10
# File 'lib/reynard/object_builder.rb', line 8

def parsed_body
  @parsed_body
end

#schemaObject (readonly)

Returns the value of attribute schema.



8
9
10
# File 'lib/reynard/object_builder.rb', line 8

def schema
  @schema
end

Class Method Details

.array_model_class_set(model_name) ⇒ Object



54
55
56
57
58
# File 'lib/reynard/object_builder.rb', line 54

def self.array_model_class_set(model_name)
  return Array unless model_name

  ::Reynard::Models.const_set(model_name, Class.new(Array))
end

.model_class_get(model_name) ⇒ Object



40
41
42
43
44
# File 'lib/reynard/object_builder.rb', line 40

def self.model_class_get(model_name)
  Kernel.const_get("::Reynard::Models::#{model_name}")
rescue NameError
  nil
end

.model_class_set(model_name, schema, inflector) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/reynard/object_builder.rb', line 46

def self.model_class_set(model_name, schema, inflector)
  if schema.type == 'array'
    array_model_class_set(model_name)
  else
    object_model_class_set(model_name, schema, inflector)
  end
end

.object_model_class_set(model_name, schema, inflector) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/reynard/object_builder.rb', line 60

def self.object_model_class_set(model_name, schema, inflector)
  return Reynard::Model unless model_name

  model_class = Class.new(Reynard::Model)
  model_class.schema = schema
  model_class.inflector = inflector
  ::Reynard::Models.const_set(model_name, model_class)
end

Instance Method Details

#callObject



29
30
31
32
33
34
35
36
37
38
# File 'lib/reynard/object_builder.rb', line 29

def call
  case schema.type
  when 'object'
    model_class.new(parsed_body)
  when 'array'
    cast_array
  else
    parsed_body
  end
end

#model_classObject



21
22
23
24
25
26
27
# File 'lib/reynard/object_builder.rb', line 21

def model_class
  return @model_class if defined?(@model_class)

  @model_class =
    self.class.model_class_get(model_name) ||
    self.class.model_class_set(model_name, schema, @inflector)
end

#model_nameObject



17
18
19
# File 'lib/reynard/object_builder.rb', line 17

def model_name
  @model_name || @schema.model_name
end