views:

160

answers:

3

In SASS I can do

!pink = #ff43a7 !darker_pink = !pink - #333333

I'd like to the same in ruby.

+2  A: 

Hex can be represented in ruby by prefixing your value with 0x

pink = 0xff43a7
darker_pink = pink - 0x333333

color helper

def color(hex)
  "#%06x" % hex
end

Usage in ERb template

.container {
  color: <%= color pink %>;
  border: 1px solid <%= color darker_pink %>;
}

Output

.container {
  color: #ff43a7;
  border: 1px solid #cc1074;
}
macek
You have to add bounds checking to pin channel values at 0 and 255.
drawnonward
You should be using `#%06x` instead of just `#%x`. Otherwise, colors that start with zeroes will be formatted incorrectly. For example, a value of `0x000fff` would result in `#fff` (i.e. white, in CSS).
Todd Yandell
@Todd Yandell, I made an update. Thanks for catching this.
macek
I agree with @drawnonward; without channel clamping, the result of `0x010000 - 0x000001` is probably not what's expected when the intent is, "removed a bit of blue from this color."
Ipsquiggle
A: 

The basic approach of adding/subtracting colors in Sass is nonsense and only really works when using a gray adjustment. That's why in sass 3 we now have full support of operations in the HSL domain which maps closely to the way people think about colors.

Since Sass is written in ruby so you can at least read our code to see what's going on:

Here's the Color class.

And here's the functions that operate on them.

It really is a non-trivial set of code. Why not just use sass? :P

chriseppstein