Sha256: 91732b8843f379db6d8deb785f643df8a4163957fa2137c932b6fe9cdf872b1e

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

require "yaml"

class YamlFileStore
  DEFAULT_APP_DIRECTORY = File.join Dir.home, ".detom"
    
  def initialize(filepath=DEFAULT_APP_DIRECTORY)
    @store = {}
    @filepath = filepath
    prepare!
  end

  def each
    enumerator = @store.sort.enum_for
    
    loop do
      case current = enumerator.next
      when current.kind_of?(Array) then yield **current
      else yield current
      end
    end

    self
  end

  def path
    @filepath
  end
  
  def [](key)
    @store[key]
  end

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

  def save!
    Dir.chdir(@filepath) do
      @store.each do |key, value|
        File.open(File.join(@filepath, key), "w") {|f| YAML.dump(@store[key], f) }
      end
    end
  end

  def prepare!
    if root_directory_exists?
      # load files
      Dir.chdir(@filepath) do
        Dir["*"].each do |filename|
          @store[filename] = YAML.load File.read(File.join(@filepath, filename))
        end
      end
    else
      create_root_directory
    end
  end

  private
    def root_directory_exists?
      Dir.exist? @filepath
    end

    def create_root_directory
      Dir.mkdir @filepath
    end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
detom-0.0.2 lib/detom/yaml_file_store.rb
detom-0.0.1 lib/detom/yaml_file_store.rb