Class: ForestLiana::ResourceDeserializer

Inherits:
Object
  • Object
show all
Defined in:
app/deserializers/forest_liana/resource_deserializer.rb

Instance Method Summary collapse

Constructor Details

#initialize(resource, params) ⇒ ResourceDeserializer

Returns a new instance of ResourceDeserializer.



4
5
6
7
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 4

def initialize(resource, params)
  @params = params
  @resource = resource
end

Instance Method Details

#associated_record(type, id) ⇒ Object



66
67
68
69
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 66

def associated_record(type, id)
  resource = SchemaUtils.find_model_from_table_name(type.underscore)
  resource.find(id)
end

#column?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 62

def column?(attribute)
  @resource.columns.find {|x| x.name == attribute}.present?
end

#extract_attributesObject



17
18
19
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 17

def extract_attributes
  @params['data']['attributes'].select {|attr| column?(attr)}
end

#extract_paperclipObject



41
42
43
44
45
46
47
48
49
50
51
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 41

def extract_paperclip
  return unless @resource.respond_to?(:attachment_definitions)

  paperclip_attr = @params['data']['attributes']
    .select do |attr|
      !column?(attr) &&
        paperclip_handler?(@params['data']['attributes'][attr])
    end

  @attributes.merge!(paperclip_attr) if paperclip_attr
end

#extract_relationshipsObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 21

def extract_relationships
  if @params['data']['relationships']
    @params['data']['relationships'].each do |name, relationship|
      data = relationship['data']

      if column?(name.foreign_key) # belongs_to
        if data.is_a?(Hash)
          @attributes[name.foreign_key] = data[:id]
        elsif !data
          @attributes[name.foreign_key] = nil
        end
      elsif data # has_many
        @attributes[name] = data.map do |x|
          associated_record(x[:type], x[:id])
        end
      end
    end
  end
end

#paperclip_handler?(attr) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
57
58
59
60
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 53

def paperclip_handler?(attr)
  begin
    Paperclip.io_adapters.handler_for(attr)
    true
  rescue Paperclip::AdapterRegistry::NoHandlerError
    false
  end
end

#performObject



9
10
11
12
13
14
15
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 9

def perform
  @attributes = extract_attributes
  extract_relationships
  extract_paperclip

  @attributes
end