Created
March 30, 2019 05:00
-
-
Save ericraio/345498605ec4cc2f88822711cc338a56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class ImportService | |
class Error < StandardError | |
end | |
def initialize | |
raise ImportService::Error.new("To be implemented by subclass") | |
end | |
def importer | |
raise ImportService::Error.new("To be implemented by subclass") | |
end | |
def record_class | |
raise ImportService::Error.new("To be implemented by subclass") | |
end | |
def process_import | |
csv = importer.csv | |
download = csv.download | |
if csv.attached? && csv.download | |
CSV.parse(download) do |row| | |
if @is_non_headers_row || !importer.first_row_headers | |
record = build_record_from_row(row) | |
save_record_for_import(record) | |
end | |
@is_non_headers_row ||= true | |
end | |
else | |
importer.update_attributes(status: "invalid", invalid_reason: "#{record_class}Import::Invalid::MISSING_CSV".constantize) | |
end | |
end | |
def build_record_from_row(row) | |
record = record_class.new(account_id: importer.account_id) | |
importer.headers.each do |key, value| | |
if record.respond_to?(value) | |
record[value] = row[key.to_i] | |
else | |
record.custom_fields[value] = row[key.to_i] if value.present? | |
end | |
end | |
record | |
end | |
def save_record_for_import(record) | |
return true if record.save | |
add_record_to_invalidity_list(record) | |
update_invalid_status | |
false | |
end | |
def add_record_to_invalidity_list(record) | |
invalid_list.push(record.attributes) | |
end | |
def update_invalid_status | |
if invalid_list.length > "#{record_class}Import::Invalid::INVALID_#{record_class.to_s.underscore.upcase}S_THRESHOLD".constantize | |
importer.update_attributes(status: "invalid", invalid_reason: "#{record_class}Import::Invalid::INVALID_#{record_class.to_s.underscore.upcase}S".constantize) | |
else | |
importer.save | |
end | |
end | |
def invalid_list | |
importer.send("invalid_#{record_class.to_s.underscore.pluralize}") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment