Class: Spritely::Cache

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

Overview

‘Cache` is responsible for generating and fetching the current sprite cache `value. It is used to determine whether to generate a new sprite map or not.

Passing in a set of objects that respond to ‘cache_key` will generate an MD5 hash that can then be stored in the image itself.

Fetching an existing cache key actually reads the PNG file itself. It scans the chunks of the PNG until it finds the ‘cache_key` keyword, returning the subsequent value found.

Constant Summary collapse

PNG_SIGNATURE_LENGTH =
8
PNG_INFO_LENGTH =
8
PNG_CRC_LENGTH =

Cyclic Redundancy Check (CRC) byte-length; www.w3.org/TR/PNG/#5Chunk-layout

4

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#filenameObject

Returns the value of attribute filename

Returns:

  • (Object)

    the current value of filename



13
14
15
# File 'lib/spritely/cache.rb', line 13

def filename
  @filename
end

Class Method Details

.busted?(filename, expected_cache_key) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/spritely/cache.rb', line 22

def self.busted?(filename, expected_cache_key)
  new(filename).key != expected_cache_key
end

.generate(*objects) ⇒ Object



18
19
20
# File 'lib/spritely/cache.rb', line 18

def self.generate(*objects)
  Digest::MD5.hexdigest(objects.collect(&:cache_key).join)
end

Instance Method Details

#keyObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/spritely/cache.rb', line 26

def key
  return @key if @key

  File.open(filename) do |file|
    file.read(PNG_SIGNATURE_LENGTH) # we first have to read the signature to fast-forward the IO#pos
    until file.eof?
      each_chunk(file) do |keyword, value|
        if keyword == 'cache_key'
          return @key = value
          break
        end
      end
    end
  end
end