Sha256: 6462cf63e781ff35c42fa2e6b5510a94146fbaeaf3ce8226ff4b4ba6d843974f
Contents?: true
Size: 1.9 KB
Versions: 6
Compression:
Stored size: 1.9 KB
Contents
require 'json' require 'bjn_inventory/hash' module BjnInventory class Context < Hash def initialize(initial_data={}) if initial_data.respond_to? :stringify_keys self.merge! initial_data.stringify_keys elsif File.directory? initial_data self.load_directory('', initial_data) elsif File.exists? initial_data self.load_file('', initial_data) else raise Errno::ENOENT, "File not found to create context: #{initial_data.inspect}" end end def load_directory(key, dir) other = _load_directory(key, dir) if key.empty? self.merge! other[''] else self.merge! _load_directory(key, dir) end end def load_file(key, file) if key.empty? self.merge! JSON.parse(File.read(file)) else self[key] = JSON.parse(File.read(file)) end end def _load_directory(key, dir) { key => Dir.entries(dir).inject({}) do |h, entry| unless entry.start_with? '.' if File.directory? File.join(dir, entry) h.merge! _load_directory(entry, File.join(dir, entry)) elsif entry =~ /\.json$/ key = entry.sub(/\.json$/, '') value = JSON.parse(File.read(File.join(dir, entry))) if h.has_key? key and h[key].respond_to? :merge! and value.is_a? Hash h[key].merge! value else h[key] = value end end end h end } end end end
Version data entries
6 entries across 6 versions & 1 rubygems