Class: ImageOptim::Cache

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

Overview

Handles image cache

Instance Method Summary collapse

Constructor Details

#initialize(image_optim, workers_by_format) ⇒ Cache

Returns a new instance of Cache.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/image_optim/cache.rb', line 8

def initialize(image_optim, workers_by_format)
  return unless image_optim.cache_dir
  @cache_dir = FSPath.new(image_optim.cache_dir)
  @cache_worker_digests = image_optim.cache_worker_digests
  @options_by_format = Hash[workers_by_format.map do |format, workers|
    [format, workers.map(&:inspect).sort.join(', ')]
  end]
  @bins_by_format = Hash[workers_by_format.map do |format, workers|
    [format, workers.map(&:used_bins).flatten!.map! do |sym|
      bin = image_optim.resolve_bin!(sym)
      "#{bin.name}[#{bin.digest}]"
    end.sort!.uniq.join(', ')]
  end]
end

Instance Method Details

#fetch(original) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/image_optim/cache.rb', line 23

def fetch(original)
  return yield unless @cache_dir

  digest = digest(original, original.image_format)
  cached = @cache_dir / digest
  return cached.size? && CachePath.convert(cached) if cached.file?

  optimized = yield

  cached.dirname.mkpath

  if optimized
    tmp = FSPath.temp_file_path(digest, @cache_dir)
    FileUtils.mv(optimized, tmp)
    tmp.chmod(0o666 & ~File.umask)
    tmp.rename(cached)
    cached_path = CachePath.convert(cached)

    # mark cached image as already optimized
    cached = @cache_dir / digest(cached, original.image_format)
    cached.dirname.mkpath
    FileUtils.touch(cached)

    cached_path
  else
    # mark image as already optimized
    FileUtils.touch(cached)
    nil
  end
end