Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

108 | Chapter 4: Database


class UserAvatar < ActiveRecord::Base
belongs_to :user
has_attachment :content_type => :image,
:max_size => 100.kilobytes,
:storage => :file_system,
:resize_to => [100, 100]
end

Attachment_fu is almost completely backward-compatible with acts_as_attachment.
Simply change theacts_as_attachmentmethod call tohas_attachment. Of course,
complete API documentation is provided with the plugin as RDoc.


Rolling your own


The attachment plugins are powerful, but they cannot do everything. If you do
decide to do your own upload processing, here are some things to take into account:



  • You must validate the uploaded data. What constitutes a valid file upload? Are
    there restrictions on the size of the uploaded data (minimum or maximum size)?
    Must the uploaded file have a certain MIME type or extension?

  • Rails can hand you any of several different types of objects, depending on what
    was uploaded and its size. James Edward Gray II has an article*on how to cor-
    rectly and efficiently handle all cases.

  • Ensure that files can be cloned properly when the associated record is cloned. (In
    the case of filesystem storage, this should just be aFileUtils.cp call.)

  • Make sure that you delete the file from storage when the record is deleted. This
    can be done with anafter_destroycallback on the model. In the case of data-
    base storage, you may find it more efficient to use a trigger or rule.


Upload progress


One feature that many applications require is upload progress notification: showing
the user a progress bar that indicates how much of the file has been uploaded. This is
surprisingly hard and server-dependent, but there are tools to make it easier. For sim-
plicity, we will restrict discussion in this section to the Mongrel application server.


Mongrel serializes Rails requests; at any given time, a single Mongrel process can
only execute one Rails request. This is required because ActionController is not
thread-safe. But upload progress requires two simultaneous requests: the upload
itself as well as AJAX requests to check its progress. How do we reconcile this?


The answer is that Mongrel is very conservative about what it locks; it only serializes
requests while they are actually executing controller code. While the file is being
transferred, Mongrel buffers it into memory, but during that time it allows other


*http://cleanair.highgroove.com/articles/2006/10/03/mini-file-uploads

Free download pdf