Module: Middleman::Imageoptim::Utils

Defined in:
lib/middleman-imageoptim/utils.rb

Class Method Summary collapse

Class Method Details

.file_size_stats(source, destination) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/middleman-imageoptim/utils.rb', line 32

def self.file_size_stats(source, destination)
  {
    source: source,
    percent_change: percentage_change(source.size, destination.size),
    size_change: format_size((source.size - destination.size)),
    size_change_type: size_change_word(source.size, destination.size)
  }
end

.format_size(bytes) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/middleman-imageoptim/utils.rb', line 19

def self.format_size(bytes)
  units = %w(B KiB MiB GiB TiB)
  if bytes.to_i < 1024
    exponent = 0
  else
    max_exp  = units.size - 1
    exponent = (Math.log(bytes) / Math.log(1024)).to_i
    exponent = max_exp if exponent > max_exp
    bytes /= 1024**exponent
  end
  "#{bytes}#{units[exponent]}"
end

.percentage_change(size_a, size_b) ⇒ Object



15
16
17
# File 'lib/middleman-imageoptim/utils.rb', line 15

def self.percentage_change(size_a, size_b)
  '%.2f%%' % [100 - 100.0 * size_b / size_a]
end

.size_change_word(size_a, size_b) ⇒ Object



4
5
6
7
8
9
10
11
12
13
# File 'lib/middleman-imageoptim/utils.rb', line 4

def self.size_change_word(size_a, size_b)
  size_difference = (size_a - size_b)
  if size_difference > 0
    'smaller'
  elsif size_difference < 0
    'larger'
  else
    'no change'
  end
end