class Excelsieur::Import
Attributes
columns[RW]
fields[RW]
result[RW]
rows[RW]
source[RW]
Public Class Methods
new(file = nil)
click to toggle source
# File lib/excelsieur/import.rb, line 22 def initialize(file = nil) self.source = file || self.class.source_file self.fields = self.class.fields @doc = ::SimpleXlsxReader.open(source) @sheet = @doc.sheets.first @columns = @sheet.rows.shift @rows = @sheet.rows @result = Result.new(@rows.length) end
Public Instance Methods
run(&block)
click to toggle source
# File lib/excelsieur/import.rb, line 35 def run(&block) check_columns! return if result.failed? if self.class.use_transaction run_with_transaction(&block) else insert_rows(&block) end result end
Private Instance Methods
add_model_errors(record, index)
click to toggle source
# File lib/excelsieur/import.rb, line 69 def add_model_errors(record, index) if record.errors.empty? report_insert return end report_failure errors[:model] << Error.new(index + 1, record.errors.full_messages) end
check_columns!()
click to toggle source
# File lib/excelsieur/import.rb, line 51 def check_columns! fields.to_a.each do |f| errors[:missing_column] << { missing: f[:header] } unless @columns.include?(f[:header]) end end
insert_row(attributes, index, &block)
click to toggle source
# File lib/excelsieur/import.rb, line 95 def insert_row(attributes, index, &block) if block_given? insert_row_with_block(attributes, &block) else insert_row_without_block(attributes, index) end end
insert_row_with_block(attributes) { |attributes| ... }
click to toggle source
# File lib/excelsieur/import.rb, line 103 def insert_row_with_block(attributes) result = yield(attributes) report_insert result rescue StandardError report_failure end
insert_row_without_block(attributes, index)
click to toggle source
# File lib/excelsieur/import.rb, line 111 def insert_row_without_block(attributes, index) record = model_class.create(attributes) add_model_errors(record, index) end
insert_rows(&block)
click to toggle source
# File lib/excelsieur/import.rb, line 88 def insert_rows(&block) @rows.map.with_index do |row, i| attributes = map_row_values(row, @columns) insert_row(attributes, i, &block) end end
model_class()
click to toggle source
# File lib/excelsieur/import.rb, line 57 def model_class self.class.name.gsub('Import', '').constantize end
report_failure()
click to toggle source
# File lib/excelsieur/import.rb, line 84 def report_failure report.failed += 1 end
report_insert()
click to toggle source
# File lib/excelsieur/import.rb, line 80 def report_insert report.inserted += 1 end
run_with_transaction(&block)
click to toggle source
# File lib/excelsieur/import.rb, line 61 def run_with_transaction(&block) model_class.transaction do insert_rows(&block) raise ActiveRecord::Rollback if report.failed.positive? end end