Today we will cover the rest of Rails’ asset pipeline, check out yesterday’s part 1 post if you missed it.
We covered how Sprockets were integrated into Rails 3.1 through Action Pack, and how the asset pipeline enables developers to benefit greatly from having their assets pre-processed, compressed and minified.
index.js as the manifest for all files in their respective directories. This means that if you have multiple
.js files in your
index.js files where you can
require these different files. Here’s a quick illustration to see how to do this in action:
You can see in both the
.js manifests that there is a
*= require_tree . for the CSS manifest and a
require_tree directive will load all of the files within the current directory. The guides also point out that we can have multiple manifest files as we need.
Development vs. Production Environments
Our assets in development mode are served in the order they were specified in our manifest file separately. Heres an example to illustrate this further:
So while we’re in our development environment, Rails will first serve
holiday.css & holiday.js, continuing to serve these files in order down the list, and generating
HTML that will load our associated files.
Since assets are compiled and cached on the first request after the server has started we can either go to
config/environments/development.rb and add
config.assets.debug = false or we can enable debug mode right inside a Rails helper methods like so:
<%= stylesheet_link_tag 'application', debug: true, if any of the files in our manifests have changed between requests, the server responds with a new compiled file instead of using the cache. It should be noted (as seen at the end of our illustration before this paragraph) that using
debug: true is redundant if we have already assigned it a
true value in our
In production Rails assumes that our assets have already been precompiled and will be served as static assets by our web server. There is a
rake task bundled with Rails that will compile our files in the asset pipeline. Our compiled assets will be written to the location specified in
config.assets.prefix which is located at
public/assets. The rake command to type in our terminals to precompile our assets is:
bundle exec rake assets:precompile. We also should remember to look at
config/application.rb and ensure that
config.assets.initialize_on_precompile = false if we plan on deploying our application to Heroku successfully.
There is a precompile array located at
config/environments/production.rb. If we have additional manifests or even individual
.js files to include, we could just add them to this array. Here is a quick illustration of this in action:
The Rails Guides mention a helpful hint to get us back on the right track:
I hope that these past couple of posts have added to your understanding and appreciate of Rails, they have done so in my case.
Categories: Ruby on rails