-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathfile_uploader.rb
43 lines (37 loc) · 1.3 KB
/
file_uploader.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
# Takes in CSV files and creates background jobs to process them
class FileUploader
attr_accessor :category,
:input_file,
:filename,
:reference,
:result_message,
:organization
UPLOADABLE_MODELS = [
Measurement,
MortalityEvent
].freeze
UPLOAD_JOBS = UPLOADABLE_MODELS.map { |model| "#{model}Job".constantize }
FILE_UPLOAD_CATEGORIES = UPLOADABLE_MODELS.map { |model| [model.to_s, model.to_s.gsub(" ", "")] }.freeze
def initialize(category:, input_file:, organization:)
@category = category
@organization = organization
@input_file = input_file
end
def process
if FILE_UPLOAD_CATEGORIES.map { |_label, value| value }.include?(category)
queue_spreadsheet
else
self.result_message = 'Error: Invalid category!'
end
self
end
def queue_spreadsheet
temporary_file = TemporaryFile.create(contents: input_file.read)
self.filename = input_file.original_filename
job_class = [category, 'Job'].join
job_class.constantize.perform_later(temporary_file, filename, organization)
self.result_message = "Successfully queued spreadsheet for import as a #{job_class}."
rescue StandardError => e
self.result_message = "Error: File could not be uploaded: #{e.message}"
end
end