Class: BjnInventory::Context

Inherits:
Hash
  • Object
show all
Defined in:
lib/bjn_inventory/context.rb

Instance Method Summary collapse

Methods inherited from Hash

#stringify_keys

Constructor Details

#initialize(initial_data = {}) ⇒ Context

Returns a new instance of Context.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/bjn_inventory/context.rb', line 8

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

Instance Method Details

#_load_directory(key, dir) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/bjn_inventory/context.rb', line 37

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

#load_directory(key, dir) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/bjn_inventory/context.rb', line 20

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

#load_file(key, file) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/bjn_inventory/context.rb', line 29

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