Reputation: 7043
I am trying to create a Tempfile using some user-inputted information in one of my models:
after_create :form_to_csv
def form_to_csv
temp_file = Tempfile.new('test_temp.csv', encoding: 'utf-8')
begin
self.input_data.split('\n').each do |line|
temp_file.write line
end
temp_file.rewind
self.build_input_data_file(file: Rails.root.join("temp_file.path}").open)
ensure
temp_file.close
temp_file.unlink
end
end
The form data is stored in the input_data
field as text. I get to write my data to the Tempfile successfully but attaching it to the model is cumbersome - I keep trying to attach nil
to my model. My main problem is that the file I generate has a path like:
/var/folders/jw/7pjlw_212qd3s4ddfj1zvnpr0000gn/T/test_temp.csv20170502-78762-1eh23ml
and it won't work with Rails.root.join and with the attachment method propose in CarrierWave docs here (Upload from a local file).
Upvotes: 0
Views: 2531
Reputation: 7043
My mistake was that I tried to assign a .csv extension within the filename parameter of the Tempfile object. Instead I needed to pass an array like this:
def form_to_csv
temp_file = Tempfile.new(['test_temp', '.csv'], encoding: 'utf-8')
begin
self.input_data.split('\n').each do |line|
temp_file.write line
end
temp_file.rewind
self.build_input_data_file(file: Rails.root.join(temp_file.path).open)
ensure
temp_file.close
temp_file.unlink
end
end
Upvotes: 2