Module: PufferPages::Backends::Mixins::Importable::ClassMethods

Defined in:
lib/puffer_pages/backends/models/mixins/importable.rb

Instance Method Summary collapse

Instance Method Details

#export_jsonObject



8
9
10
# File 'lib/puffer_pages/backends/models/mixins/importable.rb', line 8

def export_json
  all
end

#import_destroyObject



12
13
14
# File 'lib/puffer_pages/backends/models/mixins/importable.rb', line 12

def import_destroy
  destroy_all
end

#import_json(json) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/puffer_pages/backends/models/mixins/importable.rb', line 16

def import_json json
  data = json.is_a?(String) ? ActiveSupport::JSON.decode(json) : json.map(&:stringify_keys!)

  import_destroy

  data.each do |attributes|
    associations = attributes.keys.each_with_object({}) do |attribute, hsh|
      if scoped.reflect_on_association(attribute.to_sym)
        hsh[attribute] = attributes.delete(attribute)
      end
    end

    attributes = attributes.with_indifferent_access
    record = scoped.create!(attributes) do |record|
      record.id = attributes[:id] if attributes[:id].present?
    end

    associations.each do |association, attributes|
      record.send(association).import_json(attributes)
    end
  end
end