-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
import_service.rb
65 lines (57 loc) · 1.46 KB
/
import_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
require 'csv'
module Rebels
class ImportService < ServiceBase
PreconditionFailedError = Class.new(StandardError)
attr_reader :csv_import
def run(params = {})
context = {
params: params
}
catch_error(context: context) do
run!(params)
end
end
def run!(params = {})
@csv_import = CsvImport.new(csv_import_params(params))
if @csv_import.valid?
process_csv(@csv_import.content)
true
else
false
end
end
private
def csv_import_params(params)
params
.require(:csv_import)
.permit(
:content
)
end
def process_csv(content)
csv = CSV.parse(content, headers: false)
row_line = 0
csv.each do |row|
ActiveRecord::Base.transaction do
rebel_params = {
rebel: {
local_group_id: row[0]&.strip,
name: row[1]&.strip,
email: row[2]&.strip,
phone: row[3]&.strip,
postcode: row[4]&.strip,
language: row[5]&.strip&.downcase
}
}
service = Rebels::CreateService.new(source: "admin")
if service.run(ActionController::Parameters.new(rebel_params))
@csv_import.imports_count += 1
else
@csv_import.import_errors << "Line #{row_line}: #{service.error_message}"
end
end
row_line += 1
end
end
end
end