First encounter with the Rails asset pipeline and Coffeescript

Posted on October 30, 2011

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("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.


Would you like to see more Elixir content like this? Sign up to my mailing list so I can gauge how much interest there is in this type of content.