class RailsAdminImport::Formats::XLSXImporter

Public Class Methods

new(import_model, params) click to toggle source
# File lib/rails_admin_import/formats/xlsx_importer.rb, line 11
def initialize(import_model, params)
  super
  @header_converter = RailsAdminImport.config.header_converter
end

Public Instance Methods

each_record() { |attr| ... } click to toggle source

A method that yields a hash of attributes for each record to import

# File lib/rails_admin_import/formats/xlsx_importer.rb, line 17
def each_record
  doc = SimpleXlsxReader.open(filename)
  sheet = doc.sheets.first
  @headers = convert_headers(sheet.headers)
  sheet.data.each do |row|
    attr = convert_to_attributes(row)
    yield attr unless attr.all? { |field, value| value.blank? }
  end
end

Private Instance Methods

convert_headers(headers) click to toggle source
# File lib/rails_admin_import/formats/xlsx_importer.rb, line 29
def convert_headers(headers)
  headers.map do |h|
    @header_converter.call(h || "")
  end
end
convert_to_attributes(row) click to toggle source
# File lib/rails_admin_import/formats/xlsx_importer.rb, line 35
def convert_to_attributes(row)
  row_with_headers = @headers.zip(row)
  row_with_headers.each_with_object({}) do |(field, value), record|
    next if field.nil?
    field = field.to_sym
    if import_model.has_multiple_values?(field)
      field = import_model.pluralize_field(field)
      (record[field] ||= []) << value
    else
      record[field] = value
    end
  end
end