halostatue / color

Color tools for Ruby.
Other
133 stars 41 forks source link

Add Spectrum's functionality #2

Closed trans closed 10 years ago

trans commented 12 years ago

Came across this project today: https://github.com/twoism-dev/Spectrum. It's a rather small set of functions for extracting color references from strings.

Seems like that could be a good addition to color gem, and can do it better since it can return actual Color objects.

So maybe something like:

Color.extract_names('I love the color red, blue is awful') => { "red"=>RGB [#ff0000], "blue"=>RGB [#ff00ff] }
Color.extract_css('I love the color #f00, #00f is awful') => { "#f00"=>RGB [#ff0000], "#00f"=>RGB [#ff00ff] }

Also, it would be cool to get the CSS name given the html string.

r = Color::CSS::Red
r.css_name  #=> "red"

Taking it one step further, maybe even return the closest matching name, if there is no exact match.

r = Color::RGB.from_html("#ff1111")
r.css_name  #=> "red"
halostatue commented 12 years ago

Sounds interesting. I don't have time to work on this at the moment (paying work, work on my wife's novel, and gem work on libraries that I consider more important/relevant) but your proposed API isn't a bad one. The only thing that I'd probably do differently is that I probably wouldn't have #css_name return an inexact match unless the user requested it (maybe #css_nearest_names—since it could theoretically return more than one).

If you want to work up a pull request, I'd be happy to consider it for inclusion.

trans commented 12 years ago

Cool. I don't have time at the moment either, but I'll try to get to it sooner rather then later.

halostatue commented 10 years ago

These methods are going to be hung off Color::RGB. The functionality is:

Color::RGB.by_hex('0ff') # => Color::RGB::Cyan
Color::RGB.by_hex('333') # => Color::RGB.from_hex('333')
Color::RGB.by_name('cyan') # => Color::RGB::Cyan
Color::RGB.by_name('cyanide') # => raise KeyError
Color::RGB.by_css('0ff') # => Color::RGB::Cyan
Color::RGB.by_css('333') # => Color::RGB.from_hex('333')
Color::RGB.by_css('cyan') # => Color::RGB::Cyan
Color::RGB.by_css('cyanide') # => raise ArgumentError

I've made it so that Color::CSS[name] calls Color::RGB.by_name(name) instead.

As far as #extract_names is concerned, here’s the test:

      assert_equal([ Color::RGB::BlanchedAlmond, Color::RGB::Cyan ],
                   Color::RGB.extract_colors('BlanchedAlmond is a nice shade, but #00ffff is not.'))