automatic color palette for Rails

It’s difficult trying to standardize colors across a site. I picked up a tip somewhere to keep a legend at the top of a stylesheet, something like this;

F9F9FF off white
4a443c main text
B34700 link text
FF6600 action link text
eeeeee tiger body

Then you have an easy hex color reference right at the top of your main stylesheet. But “easy” becomes relative. On Hopville, I ended up describing shades of green as “medium”, “medium light”, “lightest”, and “extra-lightest”. Extra-lightest green? Which one was that again? And as the site’s color scheme has evolved, the legend has gotten out of date.  Some of the colors on the site aren’t in the legend any more, some of the colors in the legend aren’t in use anymore, and so on.
It just occurred to me that this could be automated, that I could scan all the stylesheets with a script, pull out the color attributes, and generate a color swatch page on the fly.  So when I want “that one shade of green”, I can go look it up and cut and paste the hex value, without having to dig through stylesheets or maintain a color palette legend.  Rails made it easy to generate it on the fly with an erb template (ignoring MVC for simplicity’s sake) and not even have to set up a cronjob.

Dynamic color palette browser created from stylesheets in Rails.

Dynamic color palette browser created from stylesheets in Rails.

The code:

stylesheet_dir = RAILS_ROOT + '/public/stylesheets'
files =
css_files = []
colors_in_stylesheets = {}

files.each do |file|
  if file.match(/\.css$/) + '/' + file).each do |line|
        if line.match(/\#([0-9a-f]{3,6})\;/i)
          unless colors_in_stylesheets[file]
            colors_in_stylesheets[file] = {}
          colors_in_stylesheets[file][$1.downcase] = 1

block_size = 100

<style type="text/css"> {
  width:<%= block_size %>px;
  height:<%= block_size %>px;
  border:1px dotted #ccc;
} span {
  border:1px dotted #ccc;
h2 { clear:left; }

<h1>Color Swatch</h1>
<% colors_in_stylesheets.keys.sort{|a,b|
   colors_in_stylesheets[b].size <=> colors_in_stylesheets[a].size
   }.each do |stylesheet| %>
  <h2><%= stylesheet %></h2>
  <% colors_in_stylesheets[stylesheet].sort.each do |color, garbage| %>
    <div class="swatch-block" style="background-color:#<%= color %>;">
    <span><%= color %></span>
  <% end %>
<% end %>

This works great for me since I always use hex colors, but I imagine it could be tweaked to find other color definitions as well.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: