Skip to content

Instantly share code, notes, and snippets.

@IanVaughan
Forked from augustl/application_helper.rb
Created April 29, 2010 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanVaughan/384380 to your computer and use it in GitHub Desktop.
Save IanVaughan/384380 to your computer and use it in GitHub Desktop.
def path_to_attachment_image(attachment)
image_path("attachments/#{attachment.filename}")
end
# The simplest thing that could possibly work.
class Attachment < ActiveRecord::Base
before_save :store_metadata, :if => :store_file?
after_save :store_file, :if => :store_file?
# Virtual attribute that stores the uploaded tempfile
attr_accessor :uploaded_file
private
def store_metadata
self.original_filename = uploaded_file.original_filename
self.size = uploaded_file.size
self.content_type = uploaded_file.content_type
self.filename = Digest::SHA1.hexdigest(Time.now.to_s) + self.original_filename
end
def store_file
File.open(file_storage_location, "w") {|f| f.write uploaded_file.read }
end
def store_file?
!uploaded_file == nil
end
def file_storage_location
File.join(Rails.root, 'public', 'attachments', self.filename)
end
end
<% form_for @attachment, :multipart => true do |f| %>
<%= f.file_field :uploaded_file %>
<%= f.submit "Upload file" %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment