Search code examples
cssrubyruby-on-rails-3formattingconditional-statements

Excel-Style Conditional Formatting for Numbers in Rails


I'm writing a sales app where items have a :savings attribute that ranges from 0 to 100 (%). I'm hoping to have the background color of the cell in which that attribute is displayed to be conditionally colored like you can do in Excel.

The basic idea of Excel conditional formatting is it figures out the range you're dealing with (0-100), and when you assign one color to each extreme, it automatically figures out what the colors of the in between items should be. So 100 may be bright green, 80 mild green, 60 yellow, 40 orange, 20 mild red, 0 bright red. Etc.

I think I could figure out how to do this in an exhaustive sense -- just create a helper that assigns a CSS class with a different hex background color for each integer possibility between 0 and 100. But that seems terribly inefficient, and I'm crossing my fingers for some sort of Rails technique, gem, or pre-existing helper that could make this easier and more elegant.

Any ideas?


Solution

  • I wrote a jQuery plugin that does this: jQuery Hottie. I've used it a lot. Seemed like a great alternative to doing it in Rails.

    JSFiddle example.

    It's fairly simple to pass in a custom color array to map high/mid/low values to particular colors.