stable-badge

Ubiquo media

This plugin provides a media management system for Ubiquo. Once installed, you will be able to:

1 Media attachments

1.1 Add media to a model

In your model, add:

media_attachment :images

This is the simplest definition, and will provide an association called :images to Assets, that will use the default options. You can provide other options to this method, for example:

class ExampleModel < ActiveRecord::Base media_attachment :images, :size => 2, :types => %w{image} # ....... end

size and types options are optional. By default size is 1 (only one asset can be added), and accepts any type of asset.

Use :size => :many to specify that you want a undetermined number of assets.

For convention, the attribute name should be always plural no matter if it contains a single element (:size => 1). The media_attachment accessor always returns an array, so naming it in plural will remind you when you use this association in the code.

1.1.1 Minimum amount of assets

As we have seen, :size allows you to cap the maximum amount of related assets.

If you need to set the minimum, you can use the :required option:

# validations will fail if :logo is not present media_attachment :logo, :required => true # validations will fail if there aren't two images media_attachment :images, :size => 2, :required => true # validations will fail if there isn't at least one video media_attachment :videos, :size => 2, :required => 1 # in :many associations, using true is an alias for at least one media_attachment :documents, :size => :many, :required => true

This option creates a validation in somewhat similar to:

validates_presence_of :images_asset_relations

If you need to customize it in your model, don’t use the :required option and add the one that suits you in your model. See the method “required_amount_of_assets_in_#{field}” for more information.

Note that you can’t use validates_presence_of :images because the association that is filled in the forms is the one in the join table. :images will only be correct after the save, not before.

1.1.2 Media types

The available types are the AssetType instances. By default, Ubiquo includes a generic set of asset types. You can see them by:

$ script/console Loading development environment (Rails 2.3.2) >> pp AssetType.all.inject({}){|acc, at| acc[at.key] = at.name; acc} {"audio"=>"Audio", "doc"=>"Document", "image"=>"Image", "video"=>"Video", "other"=>"Other", "flash"=>"Flash"} => nil

The types in the :type option of the media_attachment method are the keys of the hash printed in the script/console example.

Also, if you want to use all types, you can set it to :ALL. It’s an special value (and the default one).

1.2 Insert media selector to the form

Once you have added a media_attachment to the model, you’ll want to display the media selector in its form. To do that just call the helper:

<% form_for ... do |form| %> .... <%= form.media_selector :images, :visibility => 'public' %> .... <% end %>

The first attribute is the name of the media attachment. :visibility can be either ‘public’ or ‘protected’. This visibility determines if the resource can be accessed from anywhere(public) or requires to login in Ubiquo(protected). Default is public.

1.3 Get the resource url

To get the url of a resource you can use url_for_media_attachment helper. In the following example we can see how to create a link to a resource:

<%= link_to( "a link to the first image", url_for_media_attachment(object.images.first) ) %>

1.4 Get the resource name

When an asset is associated with an object, this association can have a unique name.

This is useful when you set a generic name like the filename when uploading the asset, but in the association you want a different name (e.g. to be used as an image footer or alternative text)

Example of creating a link to a resource showing their custom name:

<%= link_to( object.name_for_asset(:images, object.images.first), url_for_media_attachment(object.images.first) ) %>

1.5 Get the thumbnail url

The url_for_media_attachment accepts an argument specifying a resource version. Versions are defined in the configuration. To see it just put that in script/console:

$ script/console Loading development environment (Rails 2.3.2) >> Ubiquo::Config.context(:ubiquo_media).get(:media_styles_list) => {:thumb=>"100x100>"}

Then, to get this version url just type something like that:

<%= link_to( "a link to the first image thumbnail", url_for_media_attachment(object.images.first, :thumb) ) %>

2 Media selector

When adding a media selectior initially you will see something like that: Media selector initial state

Here, you can add new media or select existent.

2.1 Add new asset

If you choose to add a new file, you just have to enter their name and select it. Then click in the ‘save’ button, the file will be ajax-uploaded and added to the selection automatically.

2.2 Select existing asset

If the ‘select existent asset’ option is selected, a search form will appear. Media selector selecting state

Here you can search existent assets by their name and select it.

2.3 Change associated text

When an asset is selected it has it’s own name and an association name. This name is only for that relation and can be changed from the selected item view: Media selector selected state

just click in the ‘change text’ link.

3 Image styles

When in your project you have specific requirements of defined sizes for images it’s useful to define a custom format. This way, when you upload an image, a copy of that image is generated with the defined size.

On config/initializers/ubiquo_config.rb do:

Ubiquo::Config.context(:ubiquo_media).get(:media_styles_list).merge!({ :vertical_banner => '60x200#', :avatar => '70x70#', :big => '640x480#', :header => '992x148#' } )

Then you can use that version in the application:

url_for_media_attachment(object.images.first, :vertical_banner)

Each format means more storage and processing time required for every image uploaded.

4 Ubiquo show helpers

For show pages, there are a couple of helpers that can help you to brainlessly print a list of images and documents.

Images
ubiquo_show_media_attachment_images( @instance, :media_field, 'Images list' )
Documents
ubiquo_show_media_attachment_docs( @instance, :media_field, 'Documents list' )

5 Media processors

5.1 Add media processors

Processors let you pass the uploaded image or file through n:Number Processors, returning the processed file/image. By default, Ubiquo has the :thumbnail processor. In order to add a new processor, for example one named “watermark”, in config/initializers/ubiquo_config.rb you should add:

default_media_processors = Ubiquo::Config.context(:ubiquo_media).get(:media_processors_list) app_processors = [:watermark] Ubiquo::Config.context(:ubiquo_media).set do |config| config.media_processors_list = app_processors + default_media_processors end

5.2 Add a watermark

Continuing with the watermark example, in order to add that watermark functionality that corresponds to the processor, you should create the folder RAILS_ROOT/lib/paperclip_processors and add a file named “watermark.rb” to that folder with that code:

module Paperclip class Watermark < Processor class InstanceNotGiven < ArgumentError; end def initialize(file, options = {},attachment = nil) super @file = file @current_format = File.extname(@file.path) @basename = File.basename(@file.path, @current_format) @watermark = Rails.root.join('/public/images/rails.png').to_s @current_geometry = Geometry.from_file file # This is pretty slow @watermark_geometry = watermark_dimensions end def watermark_dimensions return @watermark_dimensions if @watermark_dimensions @watermark_dimensions = Geometry.from_file @watermark end def make dst = Tempfile.new([@basename, @format].compact.join(".")) watermark = " \\( #{@watermark} -extract #{@current_geometry.width.to_i}x#{@current_geometry.height.to_i}+#{@watermark_geometry.height.to_i / 2}+#{@watermark_geometry.width.to_i / 2} \\) " command = "-gravity center " + watermark + File.expand_path(@file.path) + " " +File.expand_path(dst.path) begin success = Paperclip.run("composite", command.gsub(/\s+/, " ")) rescue PaperclipCommandLineError raise PaperclipError, "There was an error processing the watermark for #{@basename}" if @whiny_thumbnails end dst end end end

This code was taken from http://kairichardkoenig.de/2009/07/30/watermarking-images-with-paperclip-in-rails/

6 Use of different storage mode

Ubiquo Media currently supports two different storage systems: filesystem (default) and s3.

6.1 Configure a project to use s3

This is a step by step, recipe like tutorial, to use ubiquo media with s3 storage system

1. Add the s3 gem to your Gemfile.

gem "s3"

2. Edit config/initializers/ubiquo_config.rb and add the following lines

Ubiquo::Config.context(:ubiquo_media).set do |config| config.media_storage = :s3 end

3. Create a config/s3.yml file and populate it with the following content:

ENVIRONMENT: access_key_id: YOUR_ACCESS_KEY_ID secret_access_key: YOUR_SECRET_ACCESS_KEY bucket: YOUR_BUCKET

5. Replace the previous upcase variables with your own data. Example:

production: access_key_id: 1234567abcd secret_access_key: abcdefghijk12345 bucket: a_bucke_name

7 Using an Apache-based upload progress bar

There is a progress bar functionality available for apache based environments. In a few steps, we will see how it can be accomplished:

  1. Install and activate drogus’ apache-upload-progress-module from https://github.com/drogus/apache-upload-progress-module. Installation is well documented at source page
  2. Activate progress bar through the config option
Ubiquo::Config.context(:ubiquo_media).set do |config| config.progress_bar = true end

And that’s all folks! Progress bar is ready to run for your media uploads

8 Crop and resize

The images can be cropped or select the part of the image for each format or style defined. This feature is builtin by default so nothing special have to be done.

The advanced form can be accessed form the assets tab and from any media selector.

Media selector with advanced link

The “advanced” link brings a popup like that:

Advanced edit form

8.1 Localize format names

Image formats are defined as usual in the application but we can localize the names. The formats will be shown in the “Predefined formats” tab:

Advanced edit predefined formats tab

As you can see there appears the names of each format. These labels show the :humanize of the key by default but you can define them by defining the i18n key “ubiquo.media.styles.#{style}.name”.

en: ubiquo: media: styles: vertical_banner: name: Vertical banner avatar: name: Avatar big_format: name: Big format

8.2 Keeping backups

By default, the advanced edit form keeps a backup of the original uploaded file allowing to undo all changes done.

The “Restore to uploaded file” is only available when editing from the Assets list.

If you don’t want this feature, you can disable the backups by configuration on initializers:

Ubiquo::Config.context(:ubiquo_media).set(:assets_default_keep_backup, false)

9 I18n connector

Ubiquo media provides a builtin i18n connector. Activating it, you can share a media_attachment between the different translations of an object.

If you want all the translations to share the same set of assets, just use the :translation_shared option as in other associations:

# All translations will have the same set of images media_attachment :images, :translation_shared => true # Every translation will have its own set of videos media_attachment :videos

When you use :translation_shared => true, you can translate the caption (associated text) in each language. Also, the order (position) of the items is independent in each translation.

To activate this connector, just add the following line to your ubiquo_config.rb:

Ubiquo::Config.context(:ubiquo_media).set(:connector, :i18n)

You will need to reset your DB after this so the new fields are automatically added. If your project is already in production, you might need to create a new migration to do it manually:

def self.up change_table(:asset_relations, :translatable => true) {} end def self.down change_table(:asset_relations, :translatable => false) {} end

10 Changelog

Lighthouse tickets