Attachinary integration

Attachinary is an attachment management library for Ruby on Rails that can help to simplify attachment management in your application's model, including:

  • Non-intrusive integration with ActiveRecord and Mongoid model. You no longer need to maintain DB columns in your model entities for referencing uploaded images.
  • Easy to switch between a single image and multiple images for a model entity.
  • Simple integration through Rails modern Asset Pipeline.
  • Uses Cloudinary for uploading files to the cloud, transforming images and delivering files through a fast CDN.
  • Built-in integration with Cloudinary's jQuery-based direct upload from the browser, including progress indication and image preview.

After installing and setting up the Attachinary GEM, you can add any attachment attribute to your model class. The following code shows a User model entity:

class User < ActiveRecord::Base
  attr_accessible :name

  has_attachment  :avatar
  has_attachments :photos, :maximum => 3
end

The has_attachment and has_attachments methods were used to define a User that can have a single 'avatar' and up to 3 'photo' attachments. That's it, no additional migrations or code changes are required.

Uploading assets to Cloudinary is also quite simple with Attachinary. The following HAML view code shows how to create an upload form. The attachinary_file_field_tag view helper method is responsible for all the magic. When this form is submitted, all images will be automatically uploaded to the cloud directly from your website visitor's browser. Multiple photos can be uploaded from this same form and the identifiers of the uploaded images will be automatically stored in your model.

= form_for(@user) do |user_form|
    = user_form.text_field(:name)
    = attachinary_file_field_tag 'user[avatar]', @user, :avatar
    = attachinary_file_field_tag 'user[photos]', @user, :photos

    = user_form.submit("Save")

Model management in your controller is the same as always:

def create
  @user = User.new(params[:user])
  @user.save!
end

You can display uploaded images, generate thumbnails and apply image transformations by using Cloudinary's cl_image_tag. Here's an example of a view code that displays a 80x100 face detection based thumbnail of the user's avatar and a 70x50 rounded corner version of all uploaded photos:

- if user.avatar.present?
  = cl_image_tag(user.avatar.path, :width => 80, :height => 100,
                 :crop => :thumb, :gravity => :face)        
  - user.photos.each do |photo|
    = cl_image_tag(photo.path, :size => '70x50', :crop => :fill, :radius => 20)

Using Attachinary allows you to dynamically apply any image transformation supported by Cloudinary. All transformed images are generated on-the-fly in the cloud and are then cached and delivered through a fast CDN.