Rob's Tips and Tricks

Sunday, September 13, 2009

I do a lot of procedural content generation - thumbnailing, gradients, css, you name it. With luck, many of those pieces of code will make it up onto this site at some point. But today, I'd like to introduce a nice helper tool that I use across the board - Color.rb.

What's it do?

The Color class represents a web color (rgb + a) and allows manipulating it. You can create a color by values (255,0,0) or by string ('#FF0000').

You can lighten, darken, and blend colors together by percentage amounts.

Real-world Usage

So that's nice, but where would you actually use this? A simple example is parametric CSS rule generation. Here's a sample CSS file:

sample.css

1
2

body { color: #000; background: #fff; }
.grayed { color: #888; }

Obviously simplified, but it will suffice. You hard-code your values, and manually set gray to be halfway between your text and your background. Simple and clean. However, when you decide you'd like to modify your site's color scheme, it's a major pain going through and changing all the color values. A better way to set things up would be to generate your CSS using ERB, like this:

Now you can change the colors at the top, and re-use them throughout your rule set. But you can quickly see the problem. The .grayed rule really means "half way between the foreground and background colors." With simple strings for your color values, you can't achieve this. But, with the magic of the Color class, you can write your rules as you mean them and have it work automatically when you adjust your color scheme.

This is a very small sample, but I think you'll find as I have that when you have hundreds of CSS rules referencing various values, blending between colors, and so on, having the ability to manage the colors is very valuable.