Last Updated: February 25, 2016
·
2.77K
· shinn

Asset Pipeline helpers

Note: This asset pipeline Q&A only list the problems I've been facing. Please refer to the official guide for more details, it has everything you'll need.

Asset Pipeline was first introduced in Rails 3.1, when I just started to pick up Rails. It's definitely not something new but I think a quick Q&A on how to use its helpers effectively will be great for beginners; stop scratching your head when it doesn't work as expected.


  • Why application.js became application-8cfe89dd0e9231a2d49f4e2c2bc80d07.js on production?

TLDR: Because you've asset pipeline enabled.

8cfe89dd0e9231a2d49f4e2c2bc80d07 is the MD5 hash of the application.js file, it will change if the content of your application.js changed. This technique is used to cache the assets effectively, so the browser/server will know when to render/serve the updated asset.

  • I want to enable the fingerprinting on development for debugging purpose.

Set config.assets.digest = false in development.rb

  • I have a third-party javascript library, jquery.expander.js. How can I use it with asset pipeline?

Move jquery.expander.js to vendor/assets/javascripts/jquery.expander.js and add this line //= require jquery.expander right before //= require_tree . in application.js

  • I've an image, bg.jpg in app/assets/images and want to use it in sass/scss.

background-image: "<%= asset-url 'bg.jpg' %>"

  • I've a json file, /app/assets/javascripts/example.json. How to include it in script.js?

First, rename to script.js.erb and use this line: <%= asset_path 'example.json' %>

Updated: Found a good article on asset-pipeline http://coderberry.me/blog/2012/04/24/asset-pipeline-for-dummies/

1 Response
Add your response

You can also use the CSS/SCSS helpers, image-url, image-path so you don't need to use the embedded ruby syntax. From the official guide:

When using the asset pipeline, paths to assets must be re-written and sass-rails provides -url and -path helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet.

image-url("rails.png") becomes url(/assets/rails.png)
image-path("rails.png") becomes "/assets/rails.png".

The more generic form can also be used but the asset path and class must both be specified:

asset-url("rails.png", image) becomes url(/assets/rails.png)
asset-path("rails.png", image) becomes "/assets/rails.png"

over 1 year ago ·