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?
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.
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.
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.
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']
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With