Sha256: add27dd440822833ebf737af93cc78b1b8a651a1f874539b755163e6adfb821c

Contents?: true

Size: 1.58 KB

Versions: 9

Compression:

Stored size: 1.58 KB

Contents

require 'json'

module PictureTag
  # Store expensive bits of information between text files. Originally cached
  # width & heights of images in addition to digests, now just image digests.
  class Cache
    def initialize(base_name)
      @base_name = base_name
    end

    def [](key)
      data[key]
    end

    def []=(key, value)
      raise ArgumentError unless template.keys.include? key

      data[key] = value
    end

    # Call after updating data.
    def write
      return if PictureTag.config['disable_disk_cache']

      FileUtils.mkdir_p(File.join(base_directory, sub_directory))

      File.open(filename, 'w+') do |f|
        f.write JSON.generate(data)
      end
    end

    private

    def data
      @data ||= if File.exist?(filename)
                  JSON.parse(File.read(filename)).transform_keys(&:to_sym)
                else
                  template
                end
    end

    # /home/dave/my_blog/.jekyll-cache/jpt/(cache_dir)/assets/myimage.jpg.json
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    def base_directory
      File.join(PictureTag.site.cache_dir, 'jpt')
    end

    # /home/dave/my_blog/.jekyll-cache/jpt/(cache_dir)/assets/myimage.jpg.json
    #                                                 ^^^^^^^^
    def sub_directory
      File.dirname(@base_name)
    end

    # /home/dave/my_blog/.jekyll-cache/jpt/somefolder/myimage.jpg.json
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    def filename
      File.join(base_directory, @base_name + '.json')
    end

    def template
      { digest: nil }
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
jekyll_picture_tag-2.1.2 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.1.1 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.1.0 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.0.4 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.0.3 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.0.2 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.0.1 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.0.0 lib/jekyll_picture_tag/cache.rb
jekyll_picture_tag-2.0.0pre1 lib/jekyll_picture_tag/cache.rb