Verified Commit 8fe2908a authored by Alexis Reigel's avatar Alexis Reigel
Browse files

add model validation error reporting

parent 9bb16869
module Excelsior
Error = Struct.new(:row, :errors)
end
......@@ -3,6 +3,7 @@ require 'rails'
require 'active_record'
require 'excelsior/source'
require 'excelsior/mapping'
require 'excelsior/error'
module Excelsior
class Import
......@@ -26,12 +27,13 @@ module Excelsior
end
def run # takes an optional block
@rows.map do |row|
@rows.map.with_index do |row, i|
attributes = map_row_values(row, @columns)
if block_given?
yield attributes
else
model_class.create!(attributes)
record = model_class.create(attributes)
add_model_errors(record, i)
end
end
end
......@@ -52,5 +54,13 @@ module Excelsior
def model_class
self.class.name.gsub("Import", "").constantize
end
def add_model_errors(record, index)
return if record.errors.empty?
@errors[:model] ||= []
@errors[:model] << Error.new(index + 1, record.errors.full_messages)
end
end
end
......@@ -15,6 +15,7 @@ end
class ExcelsiorTest < Minitest::Test
def setup
User.delete_all
@import = UserImport.new
end
......@@ -74,4 +75,10 @@ class ExcelsiorTest < Minitest::Test
import = UserImport.new("test/files/missing-column.xlsx")
assert import.errors[:missing_column].any?
end
def test_model_validations
import = UserImport.new("test/files/missing-first-name.xlsx").tap(&:run)
assert import.errors[:model].any?
assert_equal import.errors[:model], [Excelsior::Error.new(3, ["First name can't be blank"])]
end
end
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment