<img src=“https://badge.fury.io/rb/pothoven-attachment_fu.svg” alt=“Gem Version” />
attachment_fu is a plugin by Rick Olson (aka technoweenie techno-weenie.net) and is the successor to acts_as_attachment. To get a basic run-through of its capabilities, check out Mike Clark’s tutorial.
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 four storage options for files uploaded through attachment_fu:
-
File system
-
Database file
-
Amazon S3
-
Rackspace (Mosso) Cloud Files
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
, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml
, and the Database file storage requires an extra table.
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
).
Two methods are available to models: has_attachment
and validates_as_attachment
.
This method accepts the options in a hash:
- :content_type
-
Allowed content types.
By default, all content types are allowed. Use
:image
to allow all standard image types. - :min_size
-
Minimum file size.
By default, set to
1.byte
. - :max_size
-
Maximum file size.
By default, set to
1.megabyte
. - :size
-
Minimum and maximum file size.
By default, set to
1..1.megabyte
. Overrides:min_size
and:max_size
. - :resize_to
-
Used by RMagick.
Tells RMagick how to resize images. Pass either an array specifying width and height or a geometry string. Prefixing the geometry string with a ‘c’ will crop the image to the specified size.
- :sharpen_on_resize
-
Used by RMagick.
If set to true, images are sharpened after being resized.
- :thumbnails
-
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.
If you have a polymorphic parent relationship, you can provide parent-type-specific thumbnail settings by using a pair with the type string as key and a Hash of thumbnail definitions, or a method symbol, as value. The method symbol will call the named method in order to get a dynamically-built Hash of thumbnail definitions, which gives you full flexibility. AttachmentFu automatically detects your first polymorphic
belongs_to
relationship. - :thumbnail_class
-
Which model class to use for thumbnails.
By default, the current attachment class is used.
- :jpeg_quality
-
JPEG quality settings for thumbnail resizes.
Arguments can be in multiple formats:
-
Integer from 0 (basically crap) to 100 (basically lossless, fat files).
-
When relying on tdd-image_science, you can also use one of its
JPEG_xxx
constants for predefined ratios/settings. -
You can also use a Hash, with keys being either thumbnail symbols (I repeat: symbols) or surface boundaries. A surface boundary is a string starting with either ‘<’ or ‘>=’, followed by a number of pixels. This lets you specify per-thumbnail or per-general-thumbnail-“size” JPEG qualities. (which can be useful when you have a lot of thumbnail options). Surface example:
{'<2000' => 90, '>=2000' => 75}
.
Defaults vary depending on the processor (ImageScience: 100%, Rmagick/MiniMagick/Gd2: 75%, CoreImage: auto-adjust). Note that only tdd-image_science (available from GitHub) currently supports explicit JPEG quality; the default image_science currently forces 100%.
-
- :path_prefix
-
Path to store the uploaded files in. Uses
public/#{table_name}
by default for the filesystem, and just#{table_name}
for the S3 and Cloud Files backend. Setting this sets the:storage
to:file_system
. - :partition
-
Whether to partiton files in directories like
/0000/0001/image.jpg
. Default is true. Only applicable to the:file_system
backend. - :storage
-
Specifies the storage system to use. Defaults to
:db_file
. Options are:file_system
,:db_file
,:s3
, and:cloud_files
. - :cloudfront
-
If using S3 for storage, this option allows for serving the files via Amazon CloudFront. Defaults to false.
- :processor
-
Sets the image processor to use for resizing of the attached image. Options include ImageScience, Rmagick, MiniMagick, Gd2 and CoreImage. Default is whatever is installed.
- :uuid_primary_key
-
If your model’s primary key is a 128-bit UUID in hexadecimal format, then set this to true.
- :association_options
-
attachment_fu automatically defines associations with thumbnails with
has_many
andbelongs_to
. If there are any additional options that you want to pass to these methods, then specify them here.
Examples:
has_attachment(content_type: 'application/pdf') has_attachment( content_type: ['application/pdf', 'application/msword', 'text/plain'] ) has_attachment(content_type: ['application/pdf', :image], resize_to: 'x50') has_attachment(content_type: :image, resize_to: [50,50]) has_attachment(max_size: 1.kilobyte) has_attachment(size: 1.megabyte..2.megabytes) has_attachment(storage: :cloud_files) has_attachment(storage: :file_system, path_prefix: 'public/files') has_attachment( storage: :file_system, path_prefix: 'public/files', content_type: :image, resize_to: [50, 50], partition: false ) has_attachment( storage: :file_system, path_prefix: 'public/files', thumbnails: {thumb: [50, 50], geometry: 'x50'} ) has_attachment(storage: :s3) has_attachment(store: :s3, cloudfront: true) has_attachment(thumbnails: {thumb: [50, 50], geometry: 'x50'}) # Let's say we have a polymorphic belongs_to, e.g. called 'imageable', where # imageable_type (or whatever the :foreign_type option was set to) can be, # among other things, 'Product', 'User' or 'Editorial', each of which should # have extra thumbnails: has_attachment(thumbnails: { editorials: {fullsize: '150x100>'}, geometry: 'x50', products: {large_thumb: '169x169!', zoomed: '500x500>'}, thumb: [50, 50], users: {avatar: '64x64!'} }) # JPEG qualities… has_attachment(jpeg_quality: 75) has_attachment(jpeg_quality: 80 | ImageScience::JPEG_PROGRESSIVE) has_attachment( thumbnails: {thumb: [50, 50], geometry: 'x50'}, jpeg_quality: {'<2000' => 90, '>=2000' => 75} ) has_attachment( thumbnails: {thumb: [50, 50], geometry: 'x50'}, jpeg_quality: {nil => 75, thumb: 90, geometry: 90} )
This method prevents files outside of the valid range (:min_size
to :max_size
, 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.
To perform this validation, simply add validates_as_attachment
to your model.
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. Example: # # (In Model 'Avatar') # has_attachment( # :content_type => :image, # :storage => :file_system, # :max_size => 500.kilobytes, # :resize_to => '320x200>', # :thumbnails => { # :small => '10x10>', # :thumb => '100x100>' # } # ) # # (Elsewhere) # @user.avatar.thumbnails.first.thumbnail # => 'small' # db_file_id, :integer # ID of the file in the database (foreign key) that # reference files stored in the database (:db_file).
Field for attachment_fu db_files
table:
data, :binary # binary file data, for use in database file storage
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.
-
Include
multipart: true
in the html options of theform_for
tag. Example:<%= form_for( :attachment_metadata, url: {action: "create"}, html: {multipart: true} ) do |form| %>
-
Use the
file_field
helper with:uploaded_data
as the field name. Example:<%= form.file_field(:uploaded_data) %>
Displaying uploaded images is made easy by the public_filename
method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage.
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:
attachment_obj.public_filename #=> /attachments/2/file.jpg attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg attachment_obj.public_filename(: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.
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 a view:
<%= form.file_field(:attachable, :uploaded_data) %>
In a controller:
def create @attachable_file = AttachmentMetadataModel.new(params[:attachable]) if @attachable_file.save flash[:notice] = 'Attachment was successfully created.' redirect_to(attachable_url(@attachable_file)) else redirect_to(action: 'new') end end
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 'action_controller/test_process.rb' path = "./public/images/x.jpg" # `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/,"") mimetype = "image/jpeg" # This will "upload" the file at path and create the new model. @attachable = AttachmentMetadataModel.new( uploaded_data: ActionController::TestUploadedFile.new(path, mimetype) ) @attachable.save