Module: TTYCoke::Import

Extended by:
Import
Included in:
Import
Defined in:
lib/ttycoke/import.rb

Instance Method Summary collapse

Instance Method Details

#import(result, paths, origins = {}, importer = $0) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/ttycoke/import.rb', line 5

def import result, paths, origins={}, importer=$0
  Array(paths).each do |path|
    begin
      data = YAML.load_file(importer + path)
    rescue => error
      error.message << ' when importing %s into %s' %
        [path, importer].map(&:inspect)
      raise error
    end
    mark_origin data, path, origins
    merge result, data, path, origins
  end
  result
end

#merge(dst_hash, src_hash, src_file, origins = {}, backtrace = []) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ttycoke/import.rb', line 20

def merge dst_hash, src_hash, src_file, origins={}, backtrace=[]
  src_hash.each do |key, src_val|
    backtrace.push key

    catch :merged do
      if dst_hash.key? key
        dst_val = dst_hash[key]

        dst_file = origins[dst_val]
        section = backtrace.join(':')

        if src_val.nil?
          LOG.warn 'empty section %s in %s removes value %s from %s' %
            [section, src_file, dst_val, dst_file].map(&:inspect)

          dst_hash.delete key
          throw :merged

        elsif dst_val.is_a? Hash and src_val.is_a? Hash
          merge dst_val, src_val, src_file, origins, backtrace
          throw :merged

        elsif dst_val.is_a? Array
          dst_val.concat Array(src_val)
          throw :merged

        else
          LOG.warn 'value %s from %s overrides %s from %s in section %s' %
            [src_val, src_file, dst_val, dst_file, section].map(&:inspect)
          # fall through
        end
      end
      dst_hash[key] = src_val
    end
    backtrace.pop
  end
  dst_hash
end