Class: NormalizrRuby::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/normalizr_ruby/converter.rb

Defined Under Namespace

Classes: SchemaNotFound

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ Converter

Returns a new instance of Converter.



14
15
16
17
18
# File 'lib/normalizr_ruby/converter.rb', line 14

def initialize(context)
  @context = context
  @entities = {}
  @result = nil
end

Class Method Details

.get_schema_class(resource) ⇒ Object



5
6
7
8
9
10
11
12
# File 'lib/normalizr_ruby/converter.rb', line 5

def self.get_schema_class(resource)
  resource_class_name = resource.class.base_class.name
  schema_class = "#{resource_class_name}Schema".safe_constantize
  if schema_class.nil?
    raise SchemaNotFound, "#{resource_class_name} is not found."
  end
  schema_class
end

Instance Method Details

#normalize(resource, options) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/normalizr_ruby/converter.rb', line 20

def normalize(resource, options)
  opts = options.presence || {}
  @result = walk(resource, opts)
  key_transform = NormalizrRuby.config.key_transform
  normalized_hash = { result: @result, entities: @entities }
  KeyTransform.send(key_transform, normalized_hash)
rescue SchemaNotFound => e
  resource
end

#walk(resource, options) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/normalizr_ruby/converter.rb', line 30

def walk(resource, options)
  result = nil
  if resource.respond_to?(:map)
    result = resource.map {|r| walk(r, options)}
  else
    schema_class = options[:schema].presence || self.class.get_schema_class(resource)
    schema = schema_class.new(resource, @context, options.except(:schema))
    result = schema.object.id
    entity_key = schema.object.class.base_class.name.pluralize.to_sym
    hash = schema.attributes
    schema.associations.each do |association, assoc_options|
      association_result = walk(schema.object.send(association), assoc_options)
      hash[association] = association_result
    end
    @entities[entity_key] ||= {}
    @entities[entity_key][result] = hash
  end
  result
end