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

#column?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#extract_attributesObject



17
18
19
20
21
22
23
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 17

def extract_attributes
  if @params[:data][:attributes]
    @params['data']['attributes'].select {|attr| column?(attr)}
  else
    ActionController::Parameters.new()
  end
end

#extract_paperclipObject



44
45
46
47
48
49
50
51
52
53
54
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 44

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



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 25

def extract_relationships
  if @params['data']['relationships']
    @params['data']['relationships'].each do |name, relationship|
      data = relationship['data']
      # Rails 3 requires a :sym argument for the reflect_on_association
      # call.
      association = @resource.reflect_on_association(name.try(:to_sym))

      if [:has_one, :belongs_to].include?(association.try(:macro))
        if data.is_a?(Hash)
          @attributes[name] = association.klass.find(data[:id])
        elsif data.blank?
          @attributes[name] = nil
        end
      end
    end
  end
end

#paperclip_handler?(attr) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
59
60
61
62
63
# File 'app/deserializers/forest_liana/resource_deserializer.rb', line 56

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