Class: Decidim::TermCustomizer::Import::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/decidim/term_customizer/import/importer.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initialize(file, reader = Readers::Base, parser = Parser) ⇒ Importer

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. parser - A Parser to be used during the import.



18
19
20
21
22
# File 'lib/decidim/term_customizer/import/importer.rb', line 18

def initialize(file, reader = Readers::Base, parser = Parser)
  @file = file
  @reader = reader
  @parser = parser
end

Instance Method Details

#collectionObject

Returns a data collection of the target data.



39
40
41
# File 'lib/decidim/term_customizer/import/importer.rb', line 39

def collection
  @collection ||= collection_data.map { |item| parser.new(item).parse }
end

#importObject

Public: Imports a spreadsheet/JSON to the data collection provided by the parser. The parsed data objects are saved one by one or the data collection is yielded in case block is given in which case the saving should happen outside of this class.



28
29
30
31
32
33
34
35
36
# File 'lib/decidim/term_customizer/import/importer.rb', line 28

def import
  parser.resource_klass.transaction do
    if block_given?
      yield collection
    else
      collection.each(&:save!)
    end
  end
end