The problem

Automate compression of web assets.

What we need

Get your TinyPNG API key here

gem install tinify
gem install tiny_png_checker
gem install optparse

The solution

#!/usr/bin/env ruby
# frozen_string_literal: true

# tinyficator.rb

require 'tinify'
require 'optparse'
require 'tiny_png_checker'

# NOTE: Requires Ruby 2.5 or greater.

Tinify.key = '<YOUR_API_KEY_GOES_HERE>'
Tinify.validate!

def usage
  puts 'Usage: ' +
       __FILE__ + ' [options]' \
       "\r\nOptions:\r\n" \
       "  --src DIRECTORY\tSource directory\r\n" \
       "  --dst DIRECTORY\tDestination directory"
  exit
end

def parse_options
  cwd = File.dirname(__FILE__)
  options = {}
  OptionParser.new do |opt|
    opt.on('--src SRC') { |o| options[:src] = cwd + '/' + o + '/' }
    opt.on('--dst DST') { |o| options[:dst] = cwd + '/' + o + '/' }
  end.parse!
  options
end

def compress(options)
  Dir.foreach(options[:src]) do |file|
    next if ['.', '..'].include? file

    src = options[:src] + file
    dst = options[:dst] + file
    puts ' <- Reading: ' + src
    opt = Tinify.from_file(src)
    puts ' -> Writing: ' + dst
    opt.to_file(dst)
  end
  puts '### Compression done ###'
end

def mark(dst)
  marker = TinyPngChecker::Marker.new
  puts '### Marking destination files ###'
  marker.process_pngs_on_folders([dst])
  puts '### Marking done ###'
end

def check(dst)
  checker = TinyPngChecker::Checker.new
  puts '### Checking destination folder ###'
  checker.process_pngs_on_folders([dst])
  puts '### Check done ###'
end

def main
  options = parse_options
  usage unless options.length == 2

  compress(options)
  mark(options[:dst])
  check(options[:dst])
end

main

Usage

You have to specify source and destination directories with --src and --dst respectively when executing this script, example:

./tinyficator.rb --src assets --dst compressed_assets

Thanks for reading!