20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
# File 'lib/import_export.rb', line 20
def import(filename, context)
collection = []
, *data = self.read_csv(filename)
scope_object = context[:scoped]
ActiveRecord::Base.transaction do
data.each_with_index do |data_row, index|
data_row.map{|d| d.strip! if d}
if self.before_import
if self.respond_to? self.before_import
self.send(self.before_import, data_row)
else
raise "undefined before_import method '#{self.before_import}' for #{self} class"
end
end
begin
class_or_association = scope_object ? scope_object.send(self.table_name) : self
if key_field = context[:find_existing_by]
key_value = data_row[index_of(key_field)]
element = class_or_association.send("find_by_#{key_field}", key_value) || class_or_association.new
else
element = class_or_association.new
end
Rails.logger.info "#{element.new_record? ? "Creating new" : "Updating existing"} record from #{data_row.inspect}"
self.import_fields.each_with_index do |field_name, field_index|
if field_name.include?('.')
assign_association(element, field_name, field_index, context, data_row)
else
element.send "#{field_name}=", data_row[field_index]
end
end
element.save!
collection << element
rescue Exception => e
e1 = e.exception("Invalid data found at line #{index + 2} : " + e.message)
e1.set_backtrace(e.backtrace)
Rails.logger.error e1.message
Rails.logger.error e1.backtrace.join("\n")
raise e1
end
end
end
return collection
end
|