Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Last active June 16, 2016 13:23
Show Gist options
  • Save walterdavis/42ca7f6ff1a47c177d8d05d99d16c0ce to your computer and use it in GitHub Desktop.
Save walterdavis/42ca7f6ff1a47c177d8d05d99d16c0ce to your computer and use it in GitHub Desktop.

Upload a file in Rails, parse it, then throw it away

You don't need Paperclip or Carrierwave or even an ActiveRecord model to manage file uploads in Rails if all you need to do is read the file in and extract data from it.

The Catalog class (referenced in the UploadController#create method) knows how to read a JSON file, translate and extract the data therein, and create or modify Book and Product records in the surrounding application.

By using the FileUtils.cp class method, we move the uploaded file into a known location at a known filename, so the Catalog (PORO) can do its work. The tempfile created by Rack during the upload is harvested as normal by garbage collection, but the copy we made is deleted manually after the parsing process is completed.

<!-- in /views/upload -->
<%= form_tag 'create', multipart: true do %>
<div class="field form-group">
<%= label_tag 'upload[file]', 'Upload catalog.json file' %><br>
<%= file_field_tag 'upload[file]' %>
</div>
<div class="actions form-group">
<%= submit_tag 'Upload', class: 'btn btn-primary', data: { disable_with: 'Uploading' } %>
</div>
<%- end -%>
#...
get 'upload/new'
post 'upload/create'
# ...
class UploadController < ApplicationController
before_filter :authenticate_admin!
authorize_resource :class => false
require 'fileutils'
def new
end
def create
tmp = params[:upload][:file].tempfile
file = File.join("tmp", params[:upload][:file].original_filename)
if file
FileUtils.cp tmp.path, file
Catalog.new(file)
FileUtils.rm file
redirect_to books_path
else
render action: 'new'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment