Deliver assets with Rails 4 precompile on heroku

  23 Jan 2014


By default, Rails 4 returns 404 instead of assets on Heroku.

If you have bundled rails_serve_static_assets gem, you can config serve_static_assets by:

 config.serve_static_assets = true

To deliver assets on production env, you can run rake assets:precompile task:

RAILS_ENV=production bundle exec rake assets:precompile     

But, when you are deploying to Heroku, this task will be handled by rails_12factor gem.

The problem I faced is it doesn’t precompile .png and .gif assets that are in vendor assets stylesheet. (for some reason, jstree stylesheets directory has them)

But Rails allow you to add individual files to the precompile array in config/application.rb, so I just do:

config.assets.paths << Rails.root.join( 'vendor', 'assets' )
config.assets.precompile << %w( *.gif *.png )

Rename vendor/assets/stylesheets/jstree/style.css to vendor/assets/stylesheets/jstree/style.css.erb and use Rails asset_path tag helper:

background-image: url(<%= asset_path 'jstree/32px.png' %>);

Making sure to clear old stuff before precompiling:

rm -rf tmp/cache/*
rm -rf public/assets/ Then, run the rake task:

RAILS_ENV=production bundle exec rake assets:precompile

Now, you should have *.png and *.gif written to /public/assets/jstree/

comments powered by Disqus