Class: SmartImporter::Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_importer.rb

Instance Method Summary collapse

Constructor Details

#initialize(file_path:, model:, key_attribute: id) ⇒ Importer

Returns a new instance of Importer.



10
11
12
13
14
15
16
# File 'lib/smart_importer.rb', line 10

def initialize(file_path:, model:, key_attribute: id)
  @file_path = file_path
  @model = model
  @xlsx = Roo::Spreadsheet.open(@file_path.to_s)
  @number_of_imported_records = 0
  @key_attribute = key_attribute
end

Instance Method Details

#import_allObject



18
19
20
# File 'lib/smart_importer.rb', line 18

def import_all
  import_sheets(1..@xlsx.sheets.count-1)
end

#import_sheet(sheet) ⇒ Object



22
23
24
# File 'lib/smart_importer.rb', line 22

def import_sheet(sheet)
  import_sheets(Array(sheet))
end

#import_sheets(sheet_array) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/smart_importer.rb', line 26

def import_sheets(sheet_array)
  raise 'Import sheets expects an array of sheet numbers.' unless sheet_array.to_a.all? {|i| i.is_a?(Integer) }
  logger = Logger.new(STDOUT)
  logger.info "Importing #{@entity_type.to_s.underscore.pluralize} from #{@file_path}..."
  begin
    import_these_sheets sheet_array
  rescue => exception
    logger.error "Failed to import #{@entity_type} because #{exception}"
  else
    logger.info "Done importing. Imported #{@number_of_imported_records} #{@entity_type.to_s.pluralize}."
  end
end