Last Updated: February 25, 2016
·
3.898K
· anthonator

Get your Rails 3.2 assets to precompile on Heroku

Note on Rails 4

As of Rails 4 this protip is no longer relevant.

See https://devcenter.heroku.com/articles/rails4-getting-started#rails-asset-pipeline

Compiling your assets at runtime can slow things down. Keep your app snappy by making sure Heroku precompiles your assets during slug compilation.

The Problem

When Rails compiles assets, by default, requires an environment be present to boot. This is an issue on Heroku because the config vars are not present in the environment on slug compilation. This prevents the database from being initialized.

That's why you're probably seeing something like this:

could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port xxxx?

The Solution

To get your assets to precompile on Heroku all you need to do is tell Rails to not initialize during precompile. You can do this by simply adding this line in your application.rb file:

config.assets.initialize_on_precompile = false

PS

If you have any assets that need to be precompiled but are not included in your asset manifests (application.css, application.js) then you will need to add them to the config.assets.precompile option.

config.assets.precompile = %w( blah.js bleh.css )

This is generally due to assets that need to be loaded conditionally and therefore can't reside in a global manifest. For example:

<!--[if lt IE 9]>
= javascript_include_tag "html5shiv"
= javascript_include_tag "css3-mediaqueries
<![endif]-->

In this instance, both html5shiv.js and css3-mediaqueries.js would be included in the config.assets.precompile option.

PPS

What's that? You have config vars in your coffee.js.erb file? Yeah, that's a problem. As stated above, your app doesn't have access to the environment when your assets are being precompiled. Therefore, no access to config vars. However, Heroku has a handy little experimental feature called user-env-compile that will provide config vars to the environment during compile time. Now you can use config vars in your assets without worry.

A word of warning from Heroku!

The features added through labs are experimental and may change or be removed without notice.

To enable:

heroku labs:enable user-env-compile -a myapp

To disable:

heroku labs:disable user-env-compile -a myapp

https://devcenter.heroku.com/articles/labs-user-env-compile

https://devcenter.heroku.com/articles/rails3x-asset-pipeline-cedar