Sprockets Relative URL support
Fixes relative URLs in CSS assets using Sprockets.
Each asset is resolved from Sprockets, and its relative URL will be rewritten to
use a precompiled version. By adding this preprocessor, CSS frameworks can be
minified and combined into your application.css
file without any need to
rewrite the url()
values in their CSS.
Tested Rubies:
- MRI 1.9.3, 2.0.0, 2.1.x
- JRuby 1.7.x
- Rubinius 2.2.x
Installation
Add this line to your application's Gemfile:
gem 'sprockets_relative_url'
Usage
Rails
Add the processor to the Rails asset pipeline:
# config/initializers/sprockets_relative_url.rb
Rails.application.assets
.register_postprocessor('text/css', SprocketsRelativeUrl::Processor)
Ensure referenced assets are being precompiled. For example:
# config/application.rb
config.assets.precompile << /(fonts|images)\/.*/
Standalone Sprockets
env = Sprockets::Environment.new
env.append_path('app/assets')
env.register_postprocessor('text/css', SprocketsRelativeUrl::Processor)
Similar to the Rails setup above, you will need to ensure that referenced assets are being precompiled.
Caveats
This library uses a regular expression to grab url(...)
values out of CSS,
which has some drawbacks:
No support for escaped parentheses inside URLs:
background: url(images/mainbg\(white\).png);
This issue is addressed by ignoring any URL which contains a backslash character, but this obviously means that escaped characters in a URL are prohibited. Special characters can be URL encoded to work around this.
Deliberately malformed CSS can probably trick the regular expression into matching something it shouldn't. This should never be an issue, but it's worth mentioning.
These could be fixed properly by building a full CSS parser into the processor, but the additional complexity is prohibitive.
Contributing
- Fork it ( https://github.com/smangelsdorf/sprockets_relative_url/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Verify project tests and style (
rake
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request