Skip to content

Instantly share code, notes, and snippets.

@code
Created November 3, 2008 09:43
Show Gist options
  • Save code/21838 to your computer and use it in GitHub Desktop.
Save code/21838 to your computer and use it in GitHub Desktop.
# File: kuler.rb
# Author: Luke Hubbard
# Gist: http://gist.github.com/21838
# License: MIT
# Description: Little API wrapper for Kuler, Adobe's color site. http://kuler.adobe.com. Not you need an api key!
require 'rubygems'
require 'active_support'
require 'syndication/rss'
require 'open-uri'
require 'md5'
require 'fileutils'
class Kuler
WEB_SERVICE = "http://kuler-api.adobe.com/rss/get.cfm"
cattr_accessor :api_key
cattr_accessor :items_per_page
cattr_accessor :caching_enabled
cattr_accessor :cache_dir
def self.popular(force=false)
@@popular = nil if force
@@popular ||= begin
parse(WEB_SERVICE+'?listtype=popular&timespan=30&key='+api_key+'&itemsPerPage='+items_per_page.to_s)
end
end
def self.rating(force=false)
@@rating = nil if force
@@rating ||= begin
parse(WEB_SERVICE+'?listtype=rating&key='+api_key+'&itemsPerPage='+items_per_page.to_s)
end
end
def self.random(force=false)
@@random = nil if force
@@random ||= begin
parse(WEB_SERVICE+'?listtype=latest&key='+api_key+'&itemsPerPage='+items_per_page.to_s)
end
end
def self.image(id)
"http://kuler-api.adobe.com/kuler/themeImages/theme_#{id}.png"
end
def self.link(id)
"http://kuler.adobe.com/index.cfm#themeID/#{id}"
end
def self.luminance(hexcode)
r, g, b = rgb(hexcode)
mn = [r, g, b].min;
mx = [r, g, b].max;
( mn + mx ) * 0.5;
end
def self.brightness(hexcode)
r, g, b = rgb(hexcode)
[r, g, b].max;
end
def self.darkness(hexcode)
r, g, b = rgb(hexcode)
(r + g + b) / 3;
end
def self.dark?(hexcode)
darkness(hexcode) < 128
end
def self.rgb(hexcode)
[hexcode].pack("H*").unpack("C*")
end
protected
def self.parse(feed)
parser = Syndication::RSS::Parser.new
parser.parse(read(feed)).items.collect do |it|
{:id=>it.link.split("/").last.to_i, :name=>it.title, :colors=>it.description.split("\n").last.strip.split(", ")}
end
end
def self.read(feed)
if !caching_enabled
# hit the web service
open(feed).read
else
FileUtils.mkdir_p cache_dir
md5 = MD5.new(feed).hexdigest
cache = File.join(cache_dir,md5+".feed-cache")
if File.exists?(File.join(cache_dir,md5+".feed-cache"))
open(cache).read
else
data = open(feed).read
File.open(cache, "w+") {|f| f << data }
data
end
end
end
end
Kuler.caching_enabled = true
Kuler.cache_dir = '/tmp/kuler'
Kuler.items_per_page = 100
Kuler.api_key = 'REPLACE_ME_WITH_YOUR_API_KEY_DOH'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment