Created
October 29, 2008 14:24
-
-
Save augustl/20698 to your computer and use it in GitHub Desktop.
The simplest thing that could possibly work.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def path_to_attachment_image(attachment) | |
image_path("attachments/#{attachment.filename}") | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% 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
Some of the callbacks and conditionals might be able to be simplified or removed: