Sha256: 263e8894525fad34c2d9bd0edf6a8b393c8724c2de5ee072d951cf75a6e02e74

Contents?: true

Size: 967 Bytes

Versions: 2

Compression:

Stored size: 967 Bytes

Contents

require 'tilt'
require 'erb'
require 'fileutils'
require 'json'

module Todidnt
  class Cache
    CACHE_PATH = '.todidnt/cache'

    attr_reader :time, :data

    def initialize(data)
      @time = Time.now.to_i
      @data = data
    end

    def self.save(key, data)
      # Create the destinateion folder unless it already exists.
      FileUtils.mkdir_p(CACHE_PATH)

      File.open("#{CACHE_PATH}/#{key}", 'w') do |file|
        file.write(Marshal.dump(Cache.new(data)))
      end
    end

    def self.load(key)
      return nil unless exists?(key)

      begin
        raw_cache = File.open("#{CACHE_PATH}/#{key}").read
        Marshal.load(raw_cache)
      rescue Exception
        puts "Cache file was malformed; skipping..."
        nil
      end
    end

    def self.exists?(key)
      File.exists?("#{CACHE_PATH}/#{key}")
    end

    def self.clear!
      Dir.glob("#{CACHE_PATH}/*").each do |file|
        File.delete(file)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
todidnt-0.4.1 lib/todidnt/cache.rb
todidnt-0.3.1 lib/todidnt/cache.rb