Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load css.erb files through asset pipeline

I want my stylesheet to stay plain css but I want to use embedded ruby to include some dynamic paths to images:

.home {background: #FFF url(<%= image_path 'hippopotamus.jpg' %>) no-repeat; }

If I change the stylesheet from .css to .css.erb the image_path gets interpreted correctly, but it doesn't got processed by the asset pipeline when I deploy to production. If I hard code the path in, it will be wrong either in production or development because they load assets differently.

How do I resolve this?

like image 798
emersonthis Avatar asked Sep 09 '13 18:09

emersonthis


People also ask

How do you Precompile an asset?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

What does rake assets Precompile do?

rake assets:precompile. We use rake assets:precompile to precompile our assets before pushing code to production. This command precompiles assets and places them under the public/assets directory in our Rails application. Let's begin our journey by looking at the internals of the Rails Asset Pipeline.

How does rails asset pipeline work?

The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets.


2 Answers

Here's what works:

It's fine to add .erb to .css files and use ruby/rails code. So the snippet in my question above is fine.

You have to add a line like this to your /config/environments/production.rb

config.assets.precompile = ['*.css.erb']

Then when you run RAILS_ENV=production bundle exec rake assets:precompile the fingerprinted CSS file will get generated and the image_path will be correctly inserted.

So this solved my problem.

For me, .js files are getting precompiled automatically without me adding any config options. But css or css.erb files weren't working. So this is what I'm actually using:

config.assets.precompile = ['*.js', '*.css', '*.css.erb']
like image 101
emersonthis Avatar answered Sep 18 '22 11:09

emersonthis


You simply need to precompile your assets. It's simple:

RAILS_ENV=production bundle exec rake assets:precompile

Everything will be run through Sprockets (the asset pipeline) and dumped into public/assets. Just make sure that gets deployed to production along with the rest of the app and that should be all!

like image 44
Tim Dorr Avatar answered Sep 20 '22 11:09

Tim Dorr