module CSVImporter
A class that includes CSVImporter
inherit its DSL and methods.
Example:
class ImportUserCSV include CSVImporter model User column :email end report = ImportUserCSV.new(file: my_csv).run! puts report.message
Constants
- VERSION
Attributes
config[R]
csv[R]
report[R]
Public Class Methods
included(klass)
click to toggle source
Setup DSL and config object
# File lib/csv_importer.rb, line 34 def self.included(klass) klass.extend(Dsl) klass.define_singleton_method(:config) do @config ||= Config.new end end
new(*args, &block)
click to toggle source
Defines the path, file or content of the csv file. Also allows you to overwrite the configuration at runtime.
Example:
.new(file: my_csv_file) .new(path: "subscribers.csv", model: newsletter.subscribers)
# File lib/csv_importer.rb, line 55 def initialize(*args, &block) @csv = CSVReader.new(*args) @config = self.class.config.dup @config.attributes = args.last @report = Report.new Configurator.new(@config).instance_exec(&block) if block end
Public Instance Methods
header()
click to toggle source
Initialize and return the `Header` for the current CSV file
# File lib/csv_importer.rb, line 66 def header @header ||= Header.new(column_definitions: config.column_definitions, column_names: csv.header) end
rows()
click to toggle source
Initialize and return the `Row`s for the current CSV file
# File lib/csv_importer.rb, line 71 def rows csv.rows.map.with_index(2) do |row_array, line_number| Row.new(header: header, line_number: line_number, row_array: row_array, model_klass: config.model, identifiers: config.identifiers, after_build_blocks: config.after_build_blocks) end end
run!()
click to toggle source
Run the import. Return a Report
.
# File lib/csv_importer.rb, line 94 def run! if valid_header? @report = Runner.call(rows: rows, when_invalid: config.when_invalid, after_save_blocks: config.after_save_blocks, report: @report) else @report end rescue CSV::MalformedCSVError => e @report = Report.new(status: :invalid_csv_file, parser_error: e.message) end
valid_header?()
click to toggle source
# File lib/csv_importer.rb, line 78 def valid_header? if @report.pending? if header.valid? @report = Report.new(status: :pending, extra_columns: header.extra_columns) else @report = Report.new(status: :invalid_header, missing_columns: header.missing_required_columns, extra_columns: header.extra_columns) end end header.valid? rescue CSV::MalformedCSVError => e @report = Report.new(status: :invalid_csv_file, parser_error: e.message) false end