Class: TinyPngChecker::Compressor

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

Instance Method Summary collapse

Constructor Details

#initializeCompressor

Returns a new instance of Compressor.



9
10
11
12
# File 'lib/tiny_png_checker/compressor.rb', line 9

def initialize
  @errors = []
  @processed = []
end

Instance Method Details

#compress_pngs_on_folders(folders = []) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/tiny_png_checker/compressor.rb', line 14

def compress_pngs_on_folders(folders = [])
  begin
    Tinify.key = Figaro.env.tinify_api_key
    Tinify.validate!
  rescue Tinify::Error => e
    abort("Error: Tinify invalid api key #{e}")
  end

  @errors.clear
  @processed.clear

  png_files = Utils::ImageFilesRetriever.get_png_files_from_folders(folders)

  not_processed_files = Utils::TinyPng.not_processed_files(png_files)

  not_processed_files.each { |not_processed_file| process_file(not_processed_file) }

  $stdout.puts("Compressed files:")
  $stdout.puts(@processed)

  if @errors.any?
    $stderr.puts(@errors)
    abort
  end
end

#process_file(file) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/tiny_png_checker/compressor.rb', line 40

def process_file(file)
  begin
    Tinify.from_file(file).to_file(file)
    Utils::TinyPng.mark_files(file)
    @processed << file
  rescue Tinify::AccountError => e
    @errors << "The error message is: #{e.message} with file #{file}, monthly conversion limit #{Tinify.compression_count}"
      # Verify your API key and account limit.
  rescue Tinify::ClientError => e
    @errors << "Check your source image and request options, the error message is: #{e.message} with file #{file}"
      # Check your source image and request options.
  rescue Tinify::ServerError => e
    @errors << "Temporary issue with the Tinify API, the error message is: #{e.message} with file #{file}"
      # Temporary issue with the Tinify API.
  rescue Tinify::ConnectionError => e
    @errors << "A network connection error occurred, the error message is: #{e.message} with file #{file}"
      # A network connection error occurred.
  rescue => e
    @errors << "An error occurred, the error message is: #{e.message} with file #{file}"
    # Something else went wrong, unrelated to the Tinify API.
  end
end