Sha256: cd06223d098d93076e50d7feb9441a5fe4c42d03b8078fb28872510342d9687c

Contents?: true

Size: 1.21 KB

Versions: 5

Compression:

Stored size: 1.21 KB

Contents

require "digest/md5"
require "fileutils"

module Ruco
  class FileStore
    def initialize(folder, options)
      @folder = folder
      @options = options
    end

    def set(key, value)
      FileUtils.mkdir_p @folder unless File.exist? @folder
      File.write(file(key), serialize(value))
      cleanup
    end

    def get(key)
      file = file(key)
      deserialize File.binary_read(file) if File.exist?(file)
    end

    def cache(key, &block)
      value = get(key)
      if value.nil?
        value = yield
        set(key, value)
      end
      value
    end

    def delete(key)
      FileUtils.rm(file(key))
    rescue Errno::ENOENT
    end

    def clear
      FileUtils.rm_rf(@folder)
    end

    def file(key)
      "#{@folder}/#{Digest::MD5.hexdigest(key)}.yml"
    end

    private

    def entries
      (Dir.entries(@folder) - ['.','..']).
        map{|entry| File.join(@folder, entry) }.
        sort_by{|file| File.mtime(file) }
    end

    def cleanup
      delete = entries[0...-@options[:keep]] || []
      delete.each{|f| File.delete(f) }
    end

    def serialize(value)
      @options[:string] ? value : Marshal.dump(value)
    end

    def deserialize(value)
      Marshal.load(value)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ruco-0.2.0.beta6 lib/ruco/file_store.rb
ruco-0.2.0.beta5 lib/ruco/file_store.rb
ruco-0.2.0.beta4 lib/ruco/file_store.rb
ruco-0.2.0.beta3 lib/ruco/file_store.rb
ruco-0.2.0.beta lib/ruco/file_store.rb