Tidy Stylesheets in Rails
It’s very easy for a site’s CSS to grow a single giant, brittle stylesheet. It becomes impossible to change anything because of bizarre interactions between elements, unexpected interactions, and simply because it’s just too big for anyone to understand. Much of programming is managing complexity, and I’ll share a nice technique in that vein.
I like to break down stylesheets so there’s a site-wide stylesheet with global stylings like fonts, the site’s template, and common elements. This is the file that metastasizes on you.
My solution is to break down stylesheets by controller and action, and Rails makes this quite easy:
` # app/views/layout/application.rb <%= stylesheet_link_tag *([‘global’] + @stylesheets) %> `{lang=”ruby”}
# app/controllers/application.rb class ApplicationController < ActionController::Base before_filter :add_stylesheets
def initialize @stylesheets = [] end
def add_stylesheets [”#{controller_name}/_controller”, “#{controller_name}/#{action_name}”].each do |stylesheet| @stylesheets << stylesheet if File.exists? “#{Dir.pwd}/stylesheets/#{stylesheet}.css” end end end
This code automatically loads stylesheets for the controller and the action if they exist. The subdivision allows you to make them as compact and specific as possible. If a partial needs its own code, write at the top:
` <% @styleshets « “controller/_partial_name” %> `{lang=”ruby”}
Nice and tidy.