Class: Workarea::DataFile::Csv

Inherits:
Format
  • Object
show all
Defined in:
app/models/workarea/data_file/csv.rb

Instance Attribute Summary

Attributes inherited from Format

#operation

Instance Method Summary collapse

Methods inherited from Format

#assign_password, #clean_ignored_fields, #initialize, #model_class_for, #serialize, #slug, #unit

Constructor Details

This class inherits a constructor from Workarea::DataFile::Format

Instance Method Details

#export!Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/models/workarea/data_file/csv.rb', line 31

def export!
  headers = {}
  models.each { |m| serialize_root(m).each { |r| headers.merge!(r) } }
  headers = headers.keys

  CSV.open(tempfile.path, 'w') do |csv|
    csv << headers

    models.each do |model|
      serialize_root(model).each do |row|
        csv << headers.map { |h| row[h] }
      end
    end
  end
end

#import!Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/workarea/data_file/csv.rb', line 4

def import!
  index = 2 # start at 1 and skip headers
  failed_new_record_ids = []
  options = Workarea.config.csv_import_options.merge(headers: true)

  CSV.foreach(file.path, options) do |row|
    attrs = row.to_h
    next if attrs.values.all?(&:blank?)

    id = attrs['_id'].presence || attrs['id']
    model_class = model_class_for(attrs)
    root = id.present? ? model_class.find_or_initialize_by(id: id) : model_class.new

    assign_attributes(root, attrs)
    assign_embedded_attributes(root, attrs)

    if root.save || failed_new_record_ids.exclude?(id)
      log(index, root)
    else
      operation.total += 1 # ensure line numbers remain consistent
    end

    failed_new_record_ids << id if root.new_record?
    index += 1
  end
end