class Imgo::Optimizer

Public Class Methods

new(folder, format, width, height) click to toggle source
# File lib/imgo.rb, line 10
def initialize(folder, format, width, height)
  Dir.mkdir(folder + '/originals') unless File.exists?(folder + '/originals')
  
  Dir[folder + "/**/*.{#{format}}"].each do |item|
  
    image_key = item.split('/').last
  
    begin
      upload(item, image_key.split('.').first)
    rescue => ex
      puts "There is an upload error for #{image_key} #{ex}"
    end  
  
    FileUtils.mv(item, folder + '/originals/' + image_key)
  
    transformed_url = transform(image_key, width, height)
  
    begin
      download(transformed_url, item)
    rescue => ex
      puts "There is a download error for #{image_key} #{ex}"
    end 
  end
end

Public Instance Methods

download(url, path) click to toggle source
# File lib/imgo.rb, line 60
def download(url, path)
  puts url
  puts path
  open(path, 'wb') do |file|
    file << open(url).read
  end
end
transform(image_key, width = nil, height = nil) click to toggle source
# File lib/imgo.rb, line 48
def transform(image_key, width = nil, height = nil)
  if width.present? && height.present?
    "http://res.cloudinary.com/#{ENV['cloud_name']}/image/upload/c_limit,h_#{width},w_#{height}/#{image_key}"    
  elsif width.present?
    "http://res.cloudinary.com/#{ENV['cloud_name']}/image/upload/c_scale,w_#{width},q_auto:best/#{image_key}"
  elsif height.present?
    "http://res.cloudinary.com/#{ENV['cloud_name']}/image/upload/c_scale,h_#{height},q_auto:best/#{image_key}"
  else
    "http://res.cloudinary.com/#{ENV['cloud_name']}/image/upload/q_auto:best/#{image_key}"
  end
end
upload(path, public_id) click to toggle source
# File lib/imgo.rb, line 35
def upload(path, public_id)
  puts public_id
  
  auth = {
    cloud_name: ENV['cloud_name'],
    api_key:    ENV['api_key'],
    api_secret: ENV['api_secret'],
    public_id: public_id,
  }
  
  Cloudinary::Uploader.upload(path, auth)
end