Sha256: 71ed14fabf847f8a7feed66c92fb908dea21b12945561e5bf29e32acdce51289

Contents?: true

Size: 1.29 KB

Versions: 3

Compression:

Stored size: 1.29 KB

Contents

require 'json'

module Nestene


  class FileNameConverter

    def key_to_file_name(key)
      key.gsub(/[^a-zA-Z0-9]/){|x| "_%x" % x.ord}
    end

    def file_name_to_key file_name
      file_name.gsub(/_[a-zA-Z0-9]{2}/){|x| x[1..-1].hex.chr}
    end

  end

  class DiskStorage

    def initialize(dir)
      @dir=dir
      @converter = FileNameConverter.new
    end

    def list
      entries = Dir.entries(@dir)
      entries.delete('.')
      entries.delete('..')
      entries.map!{|fn| @converter.file_name_to_key(fn)}
      entries.delete('__credentials__')
      entries
    end

    def store(key, value)
      final_name = "%s/%s" % [@dir,@converter.key_to_file_name(key)]
      tmp_name = "%s.temp" % final_name
      File.open(tmp_name,"w") do |f|
        f.write(JSON.pretty_generate(value))
      end
      File.rename(tmp_name, final_name)
    end

    def load(key)
      file_name = "%s/%s" % [@dir,@converter.key_to_file_name(key)]
      if File.exist?(file_name)
        File.open(file_name,"r"){|f| JSON.parse(f.read)}
      else
        nil
      end
    end

  end

  class MemoryStorage

    def initialize
      @storage = {}
    end

    def list
      @storage.keys
    end

    def load(key)
      @storage[key]
    end

    def store(key, value)
      @storage[key] = value
    end
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nestene-0.2.0 lib/nestene/storage.rb
nestene-0.1.8 lib/nestene/storage.rb
nestene-0.1.7 lib/nestene/storage.rb