public
Description: Treat an ActiveRecord model as a file attachment, storing its patch, size, content type, etc.
Homepage: http://weblog.techno-weenie.net
Clone URL: git://github.com/technoweenie/attachment_fu.git
Click here to lend your support to: attachment_fu and make a donation at www.pledgie.com !
eadz (author)
Sun Jun 08 21:50:07 -0700 2008
commit  65d61ed2c56292ba7c1e91cbb1ec9427f1d8e6e0
tree    3199fb9b2031182bf95fc3383d4152db7cd5878b
parent  13c7cabab3b1b160bc9314db7be3768d32c894e6
name age message
file .gitignore Tue Mar 04 20:12:28 -0800 2008 70 afu tests running just fine on JRuby w/ imag... [nicksieger]
file CHANGELOG Thu Apr 17 17:57:20 -0700 2008 Made the amazon_s3.yml file go through ERB befo... [francois]
file README.markdown Sun Jun 08 21:50:07 -0700 2008 markdown for github.com [eadz]
file Rakefile Wed Dec 13 16:59:38 -0800 2006 tests [technoweenie]
file amazon_s3.yml.tpl Sun Jan 14 10:35:00 -0800 2007 updates to s3 support with remote tests [technoweenie]
file init.rb Thu Feb 21 00:16:53 -0800 2008 Add support for Core Image in attachment_fu via... [crafterm]
file install.rb Sat Dec 23 12:04:45 -0800 2006 fix install.rb snafu [technoweenie]
directory lib/ Mon Jun 02 11:02:36 -0700 2008 Changed \w in sanitize_filename to A-Za-z0-9 in... [iffy]
directory test/ Mon Jun 02 11:11:48 -0700 2008 added tests [iffy]
directory vendor/ Thu Feb 21 00:16:53 -0800 2008 Add support for Core Image in attachment_fu via... [crafterm]
README.markdown

attachment-fu

attachmentfu is a plugin by Rick Olson (aka technoweenie http://techno-weenie.net) and is the successor to actsas_attachment. To get a basic run-through of its capabilities, check out Mike Clark's tutorial http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu.

attachment_fu functionality

attachment_fu facilitates file uploads in Ruby on Rails. There are a few storage options for the actual file data, but the plugin always at a minimum stores metadata for each file in the database.

There are three storage options for files uploaded through attachment_fu: File system Database file Amazon S3

Each method of storage many options associated with it that will be covered in the following section. Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml and the Database file storage requires an extra table.

attachment_fu models

For all three of these storage options a table of metadata is required. This table will contain information about the file (hence the 'meta') and its location. This table has no restrictions on naming, unlike the extra table required for database storage, which must have a table name of db_files (and by convention a model of DbFile).

In the model there are two methods made available by this plugins: hasattachment and validatesas_attachment.

has_attachment(options = {}) This method accepts the options in a hash: :content_type # Allowed content types. # Allows all by default. Use :image to allow all standard image types. :min_size # Minimum size allowed. # 1 byte is the default. :max_size # Maximum size allowed. # 1.megabyte is the default. :size # Range of sizes allowed. # (1..1.megabyte) is the default. This overrides the :minsize and :maxsize options. :resize_to # Used by RMagick to resize images. # Pass either an array of width/height, or a geometry string. :thumbnails # Specifies a set of thumbnails to generate. # This accepts a hash of filename suffixes and RMagick resizing options. # This option need only be included if you want thumbnailing. :thumbnail_class # Set which model class to use for thumbnails. # This current attachment class is used by default. :path_prefix # path to store the uploaded files. # Uses public/#{tablename} by default for the filesystem, and just #{tablename} for the S3 backend.
# Setting this sets the :storage to :file_system. :storage # Specifies the storage system to use.. # Defaults to :dbfile. Options are :filesystem, :db_file, and :s3. :processor # Sets the image processor to use for resizing of the attached image. # Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed.

Examples: hasattachment :maxsize => 1.kilobyte has_attachment :size => 1.megabyte..2.megabytes hasattachment :contenttype => 'application/pdf' hasattachment :contenttype => ['application/pdf', 'application/msword', 'text/plain'] hasattachment :contenttype => :image, :resize_to => [50,50] hasattachment :contenttype => ['application/pdf', :image], :resize_to => 'x50' has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } hasattachment :storage => :filesystem, :path_prefix => 'public/files' hasattachment :storage => :filesystem, :path_prefix => 'public/files', :contenttype => :image, :resizeto => [50,50] hasattachment :storage => :filesystem, :path_prefix => 'public/files', :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } has_attachment :storage => :s3

validates_as_attachment This method prevents files outside of the valid range (:minsize to :maxsize, or the :size range) from being saved. It does not however, halt the upload of such files. They will be uploaded into memory regardless of size before validation.

Example: validates_as_attachment

attachment_fu migrations

Fields for attachment_fu metadata tables... in general: size, :integer # file size in bytes content_type, :string # mime type, ex: application/mp3 filename, :string # sanitized filename that reference images: height, :integer # in pixels width, :integer # in pixels that reference images that will be thumbnailed: parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key). # Only populated if the current object is a thumbnail. thumbnail, :string # the 'type' of thumbnail this attachment record describes.
# Only populated if the current object is a thumbnail. # Usage: # [ In Model 'Avatar' ] # hasattachment :contenttype => :image, # :storage => :file_system, # :max_size => 500.kilobytes, # :resize_to => '320x200>', # :thumbnails => { :small => '10x10>', # :thumb => '100x100>' } # [ Elsewhere ] # @user.avatar.thumbnails.first.thumbnail #=> 'small' that reference files stored in the database (:db_file): dbfileid, :integer # id of the file in the database (foreign key)

Field for attachmentfu dbfiles table: data, :binary # binary file data, for use in database file storage

attachment_fu views

There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images.

There are two parts of the upload form that differ from typical usage.

  1. Include ':multipart => true' in the html options of the form_for tag. Example: <% formfor(:attachmentmetadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %>

  2. Use the filefield helper with :uploadeddata as the field name. Example: <%= form.filefield :uploadeddata %>

Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system and s3 storage.

public_filename(thumbnail = nil) Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail. Examples: attachmentobj.publicfilename #=> /attachments/2/file.jpg attachmentobj.publicfilename(:thumb) #=> /attachments/2/file_thumb.jpg attachmentobj.publicfilename(:small) #=> /attachments/2/file_small.jpg

When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document.

attachment_fu controllers

There are two considerations to take into account when using attachment_fu in controllers.

The first is when the files have no publicly accessible path and need to be downloaded through an action.

Example: def readme send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline' end

See the possible values for send_file for reference.

The second is when saving the file when submitted from a form. Example in view: <%= form.filefield :attachable, :uploadeddata %>

Example in controller: def create @attachable_file = AttachmentMetadataModel.new(params[:attachable]) if @attachable_file.save flash[:notice] = 'Attachment was successfully created.' redirectto attachableurl(@attachable_file)
else render :action => :new end end

attachement_fu scripting

You may wish to import a large number of images or attachments. The following example shows how to upload a file from a script.

!/usr/bin/env ./script/runner

required to use ActionController::TestUploadedFile

require 'action_controller' require 'actioncontroller/testprocess.rb'

@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype)) @attachable.save

This will "upload" the file at path and create the new model.

mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system

mimetype = file -ib #{path}.gsub(/\n/,"")