Class: IronAdmin::Import::Importer

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

Constant Summary collapse

PARSERS =
{
  csv: Parser::Csv,
  json: Parser::Json,
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(resource_class, file:, format:, context: nil) ⇒ Importer

Returns a new instance of Importer.



11
12
13
14
15
16
17
# File 'lib/iron_admin/import/importer.rb', line 11

def initialize(resource_class, file:, format:, context: nil)
  @resource_class = resource_class
  @file = file
  @format = format.to_sym
  @context = context
  @type_caster = TypeCaster.new
end

Instance Method Details

#execute!Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/iron_admin/import/importer.rb', line 37

def execute!
  raw_rows = parse_rows
  enforce_row_limit!(raw_rows)
  mapping = mapper.map_headers(headers_for(raw_rows))
  result_state = empty_result_state

  adapter.transaction do
    raw_rows.each_with_index do |raw_row, index|
      import_row(raw_row, index + 2, mapping, result_state)
    end
  end

  ImportResult.new(
    created_count: result_state[:created_count],
    updated_count: result_state[:updated_count],
    failed_count: result_state[:errors].size,
    errors: result_state[:errors],
    rows: result_state[:rows]
  )
end

#preview(limit: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/iron_admin/import/importer.rb', line 19

def preview(limit: nil)
  raw_rows = parse_rows
  headers = headers_for(raw_rows)
  mapping = mapper.map_headers(headers)
  preview_limit = limit || import_options.fetch(:preview_rows, 20)
  rows = raw_rows.first(preview_limit).each_with_index.map do |raw_row, index|
    build_row(raw_row, index + 2, mapping)
  end

  ImportPreview.new(
    total_rows: raw_rows.size,
    headers: headers,
    mapping: mapping,
    rows: rows,
    errors: rows.flat_map(&:errors)
  )
end