require 'open-uri' require 'csv' require 'pry' # ref: http://www.singlecolorimage.com/api.html class SingleColorImageApi BASE_URL = "http://singlecolorimage.com/get" def initialize(color_6_digest_hex:, width:, height:, download_path: nil) @color_6_digest_hex = color_6_digest_hex @width = width @height = height @download_path = download_path end def self.download(**args) new(args).download end # CSV header must be [color_6_digest_hex, width, height] def self.bulk_download(csv_file:) colors = CSV.read(csv_file, headers: true).map{|row| row.to_h.map{|k,v| [k.to_sym, v]}.to_h} colors.each do |color| puts "START #{color}" new(**color).download puts "FINISH #{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, :width, :height, :download_path def image_size "#{width}x#{height}" end def file_name "#{color_6_digest_hex}-#{image_size}.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")