Skip to content

Instantly share code, notes, and snippets.

@ab5tract
Created October 7, 2008 22:14
Show Gist options
  • Save ab5tract/15402 to your computer and use it in GitHub Desktop.
Save ab5tract/15402 to your computer and use it in GitHub Desktop.
module Palettes
module ColourLovers
class Palette
include Palettes::Mixin
# It's a Party!
require 'httparty'
include HTTParty
base_uri 'colourlovers.com'
default_params :format => 'json'
format :json
def initialize(palette_id, names=false)
get_palette(palette_id, names)
end
def get_palette(palette_id, names=false)
raise ArgumentError unless palette_id.is_a? Integer
@palette = get("api/palette/#{palette_id}")
colors = @palette['colors']
if names
cnames=[]
colors.each do |c|
cnames << get("api/color/#{c}")[:title]
end
fill colors.map! { |c| [cnames.shift, c] }
else
fill colors
end
end
def search(*keywords)
words = keywords.inject {|ret,kw| ret += "+#{kw}"} if keywords.respond_to? :last
words.gsub!(' ','+')
get("api/palettes", :query => { :keywords => words })
end
# Return the raw hash response provided by HTTParty
def response
@palette
end
end
end
end
# Palettes::Mixin
# Provides basic palette methods.
module Palettes
module Mixin
attr_reader :colors
# Palette colors may be supplied as an array of values, or an array of name/value pairs:
# Palette.new [ "#eeeeee", "#666600" ]
# Palette.new [ ["red", "#ff0000"], ["blue", "#0000ff"] ]
def fill(color_array)
@colors = color_array
end
def names
n = []
# We could use #map here, but then I'd have to use #compact
@colors.each { |c| c.respond_to?( :first ) ? n << c.first : nil }
n
end
def [](arg)
color = arg.is_a?(Integer) ? @colors[arg] : @colors.assoc(arg)
color.respond_to?(:last) ? color.last : color
end
def to_hash
Hash[ *@colors.flatten ]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment