MetaSkills.net
Coding things under other things!

Use Compass Sass Framework Files With The Rails 3.1 Asset Pipeline

The Sprockets 2 gem along with the Tilt gem make it really easy to write JavaScript or CSS using any templating language you desire. The rails defaults are CoffeeScript and Sass. About the best collection of Sass framework files for easy cross-browser CSS authoring are packaged in the compass framework. Compass even has great documentation for using their Sass framework. But what if you want to use those within the asset pipeline provided by Rails? Easy enough!

First, bundle up the compass, but do not require it. Add this to your Gemfile.

gem 'compass', :require => false

Next, add a Sass initializer in config/initializers/sass.rb and fill it in with the code below. This will add two more load paths to the Sass engine. The first is your default rails/sprockets asset path for stylesheets. It simply let's you build a deep folder structure in that directory and use relative paths from each file. The second will put the entire compass Sass framework files into the Sass load path.

Sass::Engine::DEFAULT_OPTIONS[:load_paths].tap do |load_paths|
  load_paths << "#{Rails.root}/app/assets/stylesheets"
  load_paths << "#{Gem.loaded_specs['compass'].full_gem_path}/frameworks/compass/stylesheets"
end

Now in your rails app/assets/stylesheets/foo.scss file you can use Sass' @import with paths to the compass framework.

@import "compass/css3/opacity";
#mylogo { @include opacity(0.5); }

That is an example loading up the opacity helpers. Your generated css file will look like this! CSS is never going to be the same again!

#mylogo {
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
  filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50);
  opacity: 0.5; }