Managing Styles with Sass on Heroku

UPDATE: I presented on the topics of this post at Chicago Ruby and Refresh. The video and slides are now available online. (May 1st, 2011)

I’ve generally found stylesheets to be the messiest part of any website. And I’m not surprised:

But organizing styles doesn’t have to be a mess and here’s one strategy that may make your life easier.

But First…

Since REST became the de facto way to design Rails apps, I’ve focused on organizing stylesheets by the same patterns. It just seemed natural that if you had a folder /views/users/new.html.erb you should have a similiar folder /stylesheets/users/new.css. Back in 2008, I wrote a two part post on how to do this nicely with Rails. Three years later, I’m not the only one who thinks that this is a decent idea.

But CSS has grown old and weary and is in desperate need of an update. Sass is clearly a more expressive way to define styles.

So, it seemed like a great time to refresh the way I manage styles in my Rails apps.

Why Start from Scratch?

Beware of Dog

Simply put, this was a pain in the ass. Why was it harder than it should have been?

Seriously, it shouldn’t be this god damn complicated.

FTW!

gem 'haml', '3.0.18'
$> sass-convert source.css destination.scss
Template and Styles, Happily Ever After
class AssetsApp < ActionController::Metal  
  include ActionController::Rendering

  def stylesheets
    @output = ''

    Dir.glob("#{Rails.root}/app/stylesheets/#{params[:package]}/**/*.css*") do |filename|
      sass_options = { :syntax => :scss }
      sass_options[:style] = :compressed unless Rails.env.development?

      @output += Sass::Engine.new(File.open(filename, 'r').read, sass_options).render
    end

    response.headers['Cache-Control'] = "public, max-age=#{1.year.seconds.to_i}" unless Rails.env.development?
    response.content_type = 'text/css'

    render :text => @output
  end
end
Sqoot::Application.routes.draw do |map|
  match "/stylesheets/:package.css" => AssetsApp.action(:stylesheets), :as => 'stylesheets'
end
<%= stylesheet_link_tag stylesheets_path(:package => :desktop) %>

All together now!

Published: 15 Sep 2010

Subscribe

Join the Discussion

Like what you've read?
Take issue with something I said?
Let's talk about it.