Class: Imgo::Optimizer

Inherits:
Object
  • Object
show all
Defined in:
lib/imgo.rb

Instance Method Summary collapse

Constructor Details

#initialize(folder, format, width, height) ⇒ Optimizer

Returns a new instance of Optimizer.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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

Instance Method Details

#download(url, path) ⇒ Object



60
61
62
63
64
65
66
# 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) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# 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) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# 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