class Decidim::Admin::Import::Importer

Class providing the interface and implementation of an importer. Needs a reader to be passed to the constructor which handles the import file reading depending on its type.

You can also use the ImporterFactory class to create an Importer instance.

Attributes

context[R]
creator[R]
file[R]
reader[R]

Public Class Methods

new(file:, reader: Readers::Base, creator: Creator, context: nil) click to toggle source

Public: Initializes an Importer.

file - A file with the data to be imported. reader - A Reader to be used to read the data from the file. creator - A Creator to be used during the import. context - A hash including component specific data.

# File lib/decidim/admin/import/importer.rb, line 19
def initialize(file:, reader: Readers::Base, creator: Creator, context: nil)
  @file = file
  @reader = reader
  @creator = creator
  @context = context
end

Public Instance Methods

collection() click to toggle source

Returns a collection of creators

# File lib/decidim/admin/import/importer.rb, line 39
def collection
  @collection ||= collection_data.map { |item| creator.new(item, context) }
end
import!() click to toggle source

Save resources

# File lib/decidim/admin/import/importer.rb, line 34
def import!
  collection.map(&:finish!)
end
invalid_lines() click to toggle source

Returns array of all resource indexes where validations fail.

# File lib/decidim/admin/import/importer.rb, line 44
def invalid_lines
  @invalid_lines ||= check_invalid_lines(prepare)
end
prepare() click to toggle source

Import data and create resources

Returns an array of resources

# File lib/decidim/admin/import/importer.rb, line 29
def prepare
  @prepare ||= collection.map(&:produce)
end

Private Instance Methods

check_invalid_lines(imported_data) click to toggle source
# File lib/decidim/admin/import/importer.rb, line 72
def check_invalid_lines(imported_data)
  invalid_lines = []
  imported_data.each_with_index do |record, index|
    invalid_lines << index + 1 unless record.valid?
  end
  invalid_lines
end
collection_data() click to toggle source
# File lib/decidim/admin/import/importer.rb, line 52
def collection_data
  return @collection_data if @collection_data

  @collection_data = []
  data_headers = []
  reader.new(file).read_rows do |rowdata, index|
    if index.zero?
      data_headers = rowdata.map(&:to_sym)
    else
      @collection_data << Hash[
        rowdata.each_with_index.map do |val, ind|
          [data_headers[ind], val]
        end
      ]
    end
  end

  @collection_data
end