Class: BrightSerializer::Entity::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/bright_serializer/entity/base.rb

Constant Summary collapse

DEFAULT_DEFINITION =
{ type: :undefined }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(definition) ⇒ Base



12
13
14
# File 'lib/bright_serializer/entity/base.rb', line 12

def initialize(definition)
  @definition = definition
end

Instance Method Details

#evaluate_callable!Object



32
33
34
35
36
# File 'lib/bright_serializer/entity/base.rb', line 32

def evaluate_callable!
  @definition = Inflector.deep_transform_values_in_object(@definition) do |value|
    value.respond_to?(:call) ? value.call : value
  end
end

#nested_hash(obj, key) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/bright_serializer/entity/base.rb', line 38

def nested_hash(obj, key)
  if obj.respond_to?(:key?) && obj.key?(key)
    obj
  elsif obj.respond_to?(:each)
    r = nil
    obj.find { |*a| r = nested_hash(a.last, key) }
    r
  end
end

#parse_ref!Object



23
24
25
26
27
28
29
30
# File 'lib/bright_serializer/entity/base.rb', line 23

def parse_ref!
  object = nested_hash(@definition, 'ref')
  return unless object

  ref_entity_name = object.delete('ref').constantize.entity_name
  relation = "#/definitions/#{ref_entity_name}"
  object['$ref'] = relation
end

#to_hObject



16
17
18
19
20
21
# File 'lib/bright_serializer/entity/base.rb', line 16

def to_h
  @definition = Inflector.deep_transform_keys_in_object(@definition) { |k| Inflector.camel_lower k.to_s }
  parse_ref!
  evaluate_callable!
  @definition
end