augustl (owner)

Forks

Revisions

gist: 20698 Download_button fork
public
Description:
The simplest thing that could possibly work.
Public Clone URL: git://gist.github.com/20698.git
Embed All Files: show embed
application_helper.rb #
1
2
3
def path_to_attachment_image(attachment)
  image_path("attachments/#{attachment.filename}")
end
attachment.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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
the_view.html.erb #
1
2
3
4
<% form_for @attachment, :multipart => true do |f| %>
  <%= f.file_field :uploaded_file %>
  <%= f.submit "Upload file" %>
<% end %>