Sprockets is now integrated in Rails 3.1 and is the core library behind the new Rails 3.1 asset pipeline. What about if you want to use Sprockets outside a Rails project?
Sprockets exposes a very powerful Rack interface to serve assets over HTTP. Integrating Sprockets in a Rack application, such as a Sinatra project, turns out to be a very straightforward task.
But in my case, I wanted to use Sprockets preprocessing and bundling feature outside an HTTP application. And it turned out Sprockets is very good at doing this as well.
I have a custom shared template I created several months ago called docss. I use this for several projects such as Ruby Whois and RoboWhois. The template is composed of several CSS files. I have a Ruby
rake script that merges these files and packages them into a single asset, then compress it and publish the result to Amazon CloudFront.
Instead of processing and merging the files using file system tasks I'm now delegating this task to Sprockets. The project directory structure looks like this
And here's my
First I create a new
Sprockets::Environment instance passing some configurations, such as a custom logger.
sprockets = Sprockets::Environment.new(ROOT) do |env| env.logger = LOGGER end
Then I append the asset paths.
Finally, I process and package the assets to the build directory.
Because sometimes I need to reference a single CSS file (e.g.
alignments.css) instead of the entire bundle, I also build a standalone package for each CSS source. You might not want to do that.
assets.to_a.each do |asset| # strip filename.css.foo.bar.css multiple extensions realname = asset.pathname.basename.to_s.split(".")[0..1].join(".") asset.write_to(BUILD_DIR.join(prefix, realname)) end
Please keep in mind that if you want to use processors you must include the corresponding libraries. For example, if you want to support
SASS processor you need to add the
source "http://rubygems.org" gem 'sass' gem 'sprockets'