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

(Tuis.) #1
Large/Binary Objects | 107

Serving Static Files


One advantage of filesystem storage is that as long as the file data doesn’t need to be
protected with access control or otherwise acted upon dynamically, you can leverage
your static web servers to serve that data. By exporting the storage path via NFS (or a
caching filesystem such as AFS to conserve bandwidth), you can share the applica-
tion’s files with the static servers on your content distribution network. This com-
pletely removes the load from the application servers and provides a more scalable
solution.


Managing Uploads in Rails


Most applications that use large objects must deal with uploads. This can be tricky in
any framework, but Rails handles most of the details and there are some best prac-
tices to guide you with the rest.


Attachment plugins


One of the easiest ways to handle Rails uploads is to use one of the popular plugins for
upload processing. The standard plugin used to be Rick Olson’s acts_as_attachment
(http://svn.techno-weenie.net/projects/plugins/acts_as_attachment/). Many Rails devel-
opers are familiar with its interface, and for quite a while it was the standard way to
handle uploaded data. However, there were a few factors that made it unsuitable for
many applications:



  • It is tied to RMagick (and therefore ImageMagick) for image processing.
    ImageMagick is notoriously difficult to install, primarily because it depends on
    many backend libraries for processing different image formats. At the time
    acts_as_attachment was written, ImageMagick was the best option. Now, how-
    ever, there is a lighter alternative, ImageScience, based on the FreeImage library.

  • The entire attachment data must be read into memory and converted to a Ruby
    string. For large files, this is expensive—Rails passes the application aTempFile,
    which is slurped into aString. If using filesystem storage, the string is then writ-
    ten back out into a file!

  • There is no support for alternative storage methods such as Amazon’s S3.


Luckily, there is an alternative. Rick has rewritten acts_as_attachment to resolve
these issues. The rewrite is called attachment_fu, and it is publicly available athttp://
svn.techno-weenie.net/projects/plugins/attachment_fu/.


The attachment_fu library supports all of acts_as_attachment’s options and more.
It can use RMagick as a processor, but it also supports MiniMagick (a lightweight
alternative to RMagick that still wraps ImageMagick) and ImageScience. It can store
attachments in a database, the filesystem, or S3 out of the box. It also has great
facilities for expansion; it is easy to write your own processor or storage backend.
A typical use of attachment_fu looks like this:

Free download pdf