class Decidim::TermCustomizer::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
file[R]
parser[R]
reader[R]
Public Class Methods
new(file, reader = Readers::Base, parser = Parser)
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. parser - A Parser
to be used during the import.
# 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
Public Instance Methods
collection()
click to toggle source
Returns a data collection of the target data.
# File lib/decidim/term_customizer/import/importer.rb, line 39 def collection @collection ||= collection_data.map { |item| parser.new(item).parse } end
import() { |collection| ... }
click to toggle source
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.
# 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
Private Instance Methods
collection_data()
click to toggle source
# File lib/decidim/term_customizer/import/importer.rb, line 47 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