require 'open-uri' require 'csv' require 'pry' class Color attr_reader :id, :color_name, :r, :g, :b def initialize(id:, color_name:, r:, g:, b:) @id = id @color_name = color_name @r = r @g = g @b = b end def attributes { id: id, color_name: color_name, r: r, g: g, b: b, color_6_digest_hex: color_6_digest_hex } end def color_6_digest_hex [r, g, b].map{|i| i.to_s(16) }.join end end # ref: http://www.singlecolorimage.com/api.html class SingleColorImageApi BASE_URL = "http://singlecolorimage.com/get" def initialize(color_6_digest_hex:, color_name:, id:, width: 256, height: 256, download_path: nil) @color_6_digest_hex = color_6_digest_hex @color_name = color_name @id = id @width = width @height = height @download_path = download_path end def self.download(**args) new(args).download end def self.extract_csv(csv_file:) header_mapping = { "ID" => :id, "color_library Name" => :color_name, "R" => :r, "G" => :g, "B" => :b } header_converter = lambda { |h| header_mapping[h] } csv_options = { headers: :first_row, header_converters: header_converter, converters: :integer, skip_blanks: true } rows = CSV.read(csv_file, **csv_options) rows.map{ |row| Color.new(id: row[:id], color_name: row[:color_name], r: row[:r], g: row[:g], b: row[:b]) } end # CSV header must be [color_6_digest_hex, width, height] def self.bulk_download(csv_file:) colors = extract_csv(csv_file: csv_file) colors.each do |color| puts "START #{color.attributes}" new( color_6_digest_hex: color.color_6_digest_hex, color_name: color.color_name, id: color.id ).download puts "FINISH #{color.attributes}\n" rescue => e puts e puts color end end def download open(file_path, 'w') do |f| open(request_uri) do |data| f.write(data.read) end end end private attr_reader :color_6_digest_hex, :color_name, :id, :width, :height, :download_path def image_size "#{width}x#{height}" end def file_name "#{id}.png" end def file_path File.join(donwload_dir, file_name) end def request_uri URI.join("#{BASE_URL}/", "#{color_6_digest_hex}/", image_size).tap{|t| puts t} end def donwload_dir download_path || FileUtils.mkdir_p(File.join("/tmp", "simple_images")).join end end # ex # SingleColorImageApi.download(color_6_digest_hex: "33fd8f", width: "400", height: "100") #SingleColorImageApi.bulk_download(csv_file: "color.csv") SingleColorImageApi.extract_csv(csv_file: "color_library.csv") SingleColorImageApi.download(csv_file: "color_library.csv")