First encounter with the Rails asset pipeline and Coffeescript

I was working on a Rails 3.1 project, and wanted to have some javascript image preview functionality (much like this) in several places within the project. Since this project used the new Rails 3.1, I decided I’d do my best to throw together the image preview functionality in Coffeescript and use the asset pipeline.

The code

HTML Markup

The images I wanted previews for were within HTML elements with a class of “catalog_item”. To differentiate regular links from the ones I wanted previews for, I added a “image_preview” class to the HTML anchor elements.

Coffeescript

I wanted something very similar to this (and explained in more detail here), so I based my Coffeescript on Alen Grakalic‘s javascript (original code here). This was the result:


@image_preview = () ->
$(".catalog_item a.image_link").hover(
((e) ->
$("body").append("<img id='preview' src='#{@href}' alt='Image preview' />")
$("#preview")
.fadeIn("fast");
)
(() -> $("#preview").remove())
)

Basically, when you hover over the image link, you’ll add a #preview item to the HTML body, then make it appear. In the tutorial, the image preview moves with the mouse, but I just wanted it to be displayed in a certain spot on the website. Naturally, you’ll still have to style the #preview element with CSS (e.g. using position: fixed).

I saved this file as “image_preview.js.coffee” within app/assets/javascripts.

Using the asset pipeline

Now, to leverage our Coffeescript file in multiple locations within the app: I simply included the file in the pipeline (in app/assets/javascripts/application.js) :


//= require jquery
//= require jquery_ujs
//= require image_preview
//= require_tree .

The added “//= require image_preview” directive will tell Sprockets to make our file available. Then within the Coffeescripts for each model (e.g. my catalog items), I can do the following:


$( ->
image_preview()

)

And the image preview functionality will automagically be available in my catalog item views (e.g. in the index view). All that remains is adding the proper “catalog_item” and “image_preview” classes.

This entry was posted in CoffeeScript, jQuery, Rails. Bookmark the permalink.

2 Responses to First encounter with the Rails asset pipeline and Coffeescript

  1. nitin says:

    i want to know that how to built a cms in rails

  2. david says:

    The best way to learn how to make a CMS in Rails, is to look at an existing one. Refinery (http://refinerycms.com/) is a popular open source CMS made in Rails (compatible with Rails 3.0), and you can get the source code here: https://github.com/resolve/refinerycms

Comments are closed.