Sha256: 951f9ed1f107874239336f5d9ced746d187b04f6c6e07f632396a1ed5a661280
Contents?: true
Size: 1.74 KB
Versions: 1
Compression:
Stored size: 1.74 KB
Contents
require 'fileutils' require 'pathname' require 'yaml' module Metastore class Cabinet def initialize(file) @file = Pathname.new(file).expand_path end def get(key) split_key(key).inject(contents) { |c, k| c.is_a?(Hash) ? c[k] : nil } end def set(key, value) current_contents = contents set_key_and_value(current_contents, split_key(key), value) save!(current_contents) true end def clear! save!({}) end def contents file.exist? ? YAML.load(file.read) || {} : {} end alias_method :[], :get alias_method :[]=, :set private attr_reader :file def split_key(key) key.to_s.split('.') end def set_key_and_value(input, key, value) current_key = key.shift.to_s input[current_key] = {} unless input[current_key] if key.empty? input[current_key] = recursive_stringify_keys(value) input else input[current_key] = {} unless input[current_key].is_a?(Hash) set_key_and_value(input[current_key], key, value) end end def recursive_stringify_keys(input) case input when Hash Hash[ input.map do |k, v| [ k.respond_to?(:to_s) ? k.to_s : k, recursive_stringify_keys(v) ] end ] when Enumerable input.map { |v| recursive_stringify_keys(v) } else input.is_a?(Symbol) ? input.to_s : input end end def save!(new_values) FileUtils.mkdir_p(file.dirname) unless file.exist? File.open(file.to_s, 'w') { |f| f.write(new_values.to_yaml) } rescue => e raise Errors::CabinetCannotSet.new(e.message) end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
metastore-0.2.1 | lib/metastore/cabinet.rb |