Imaginable
Imaginable is a gem for Rails, which allows easy integration with the Imagination image-upload and scaling server.
Compatibility
Imaginable is currently only compatible with Rails 3
Imaginable requires that you use jQuery. You can do this easily with the jquery-rails gem.
Dependencies
Imaginable requires that you have installed and configured the Fancybox2 jQuery plugin: http://fancyapps.com/fancybox/
Installation
Simply add Imaginable to your Gemfile and bundle it up:
gem 'imaginable'
Then run the generator to copy some javascript and a configuration initializer into your application:
$ rails generate imaginable:install
Usage
It is really easy to make a model Imaginable.
If you are creating a new model, there are even some handy migration helpers.
class CreateArticles < ActiveRecord::Migration
def self.up
create_table :articles do |t|
t.string :title
t.text :body
t.imaginable :photo
t.
end
end
def self.down
drop_table :articles
end
end
The t.imaginable
helper above, will create two columns: photo_uuid
and photo_token
which Imaginable needs to keep track of the images used by this model.
We then need to mark our model as Imaginable
class Article < ActiveRecord::Base
has_imagination :photo
end
Finally we just need to add a field to our form, which let’s the user upload a photo. This is also really easy thanks to the form helper:
<%= form_for(@article) do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="field">
<%= f.label :photo %><br />
<%= f.image_field :photo, :format => 'square' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Please note, that you need to include the Imaginable javascripts in your layout, or by other means.
Here is an example of what you could do, if you had a yield(:head)
in the head
section of your layout:
<% content_for(:head) do %>
<%= imaginable_includes_tag %>
<% end %>
That’s all there is to it!
Validation
If you require the user to upload an image, you can use this handy validation helper.
class Article < ActiveRecord::Base
has_imagination :photo
validates_presence_of :title
validates_presence_of :body
validates_imagination
end
Showing images
To show an image, you simply call the imaginable method of your model.
The method will have the name that you have configured in your model.
In the above examples, this would be @article.photo
.
<%= image_tag @article.photo.url(:format => 'square', :width => 500) %>