Prev | Current Page 158 | Next

Brad Ediger

"Advanced Rails"


A typical use of attachment_fu looks like this:
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 the acts_as_attachment method call to has_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 correctly
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 a FileUtils.cp call.)
??? Make sure that you delete the file from storage when the record is deleted. This
can be done with an after_destroy callback on the model.


Pages:
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170