Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The simplest thing that could possibly work.
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 %>
@croaky

This comment has been minimized.

Copy link

@croaky croaky commented Mar 19, 2014

Some of the callbacks and conditionals might be able to be simplified or removed:

class Attachment < ActiveRecord::Base
  after_save :store_file, :if => :filename_changed?

  def uploaded_file=(uploaded_file)
    if uploaded_file.present?
      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) + original_filename
    end
  end

  private

  def store_file
    File.open(file_storage_location, "w") {|f| f.write uploaded_file.read }
  end

  def file_storage_location
    File.join(Rails.root, 'public', 'attachments', self.filename)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment