lib/metastore/cabinet.rb in metastore-0.2.3 vs lib/metastore/cabinet.rb in metastore-0.3.0
- old
+ new
@@ -1,77 +1,80 @@
require 'fileutils'
require 'pathname'
-require 'yaml'
module Metastore
class Cabinet
- def initialize(file)
+ def initialize(file, storage_type: :yaml)
@file = Pathname.new(file).expand_path
+ @storage_type = storage_type
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!({})
- true
end
def contents
- file.exist? ? YAML.load(file.read) || {} : {}
+ storage.contents || {}
end
alias_method :[], :get
alias_method :[]=, :set
private
- attr_reader :file
+ attr_reader :file, :storage_type
+ def storage
+ @store || StorageFactory.from_sym(storage_type).new(file)
+ end
+
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[current_key] = 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)
+ def 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) ]
+ [ k.respond_to?(:to_s) ? k.to_s : k, stringify_keys(v) ]
end
]
when Enumerable
- input.map { |v| recursive_stringify_keys(v) }
+ input.map { |v| 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) }
+ storage.save!(new_values)
+ true
rescue => e
raise Errors::CabinetCannotSet.new(e.message)
end
end