Module: NSWTopo::Config

Extended by:
Forwardable
Includes:
Log
Defined in:
lib/nswtopo/config.rb

Constant Summary

Constants included from Log

Log::FAILURE, Log::NEUTRAL, Log::SUCCESS, Log::UPDATE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Log

#log_abort, #log_neutral, #log_success, #log_update, #log_warn

Instance Attribute Details

#extra_path=(value) ⇒ Object (writeonly)

Sets the attribute extra_path

Parameters:

  • value

    the value to set the attribute extra_path to.



4
5
6
# File 'lib/nswtopo/config.rb', line 4

def extra_path=(value)
  @extra_path = value
end

Class Method Details

.method_missing(symbol, *args, &block) ⇒ Object



6
7
8
9
10
# File 'lib/nswtopo/config.rb', line 6

def self.method_missing(symbol, *args, &block)
  extend(self).init
  singleton_class.remove_method :method_missing
  send symbol, *args, &block
end

Instance Method Details

#delete(*entries, key) ⇒ Object



47
48
49
# File 'lib/nswtopo/config.rb', line 47

def delete(*entries, key)
  delete_recursive @config, *entries, key
end

#delete_recursive(config, *entries, key) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/nswtopo/config.rb', line 51

def delete_recursive(config, *entries, key)
  case
  when entry = entries.shift
    raise "no such entry: %s" % entry unless Hash === config[entry]
    delete_recursive config[entry], *entries, key
    config.delete entry if config[entry].empty?
  when config.key?(key)
    config.delete key
  else
    raise "no such entry: %s" % key
  end
end

#initObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/nswtopo/config.rb', line 12

def init
  candidates = []
  %w[XDG_CONFIG_HOME APPDATA].each do |key|
    candidates << [ENV.fetch(key), "nswtopo"]
  rescue KeyError
  end
  candidates << [Dir.home, "Library", "Application Support", "com.nswtopo"]
  candidates << [Dir.home, ".config", "nswtopo"]
  candidates << [Dir.home, ".nswtopo"]

  @path = candidates.map do |base, *parts|
    Pathname(base).join(*parts)
  end.first do |dir|
    dir.parent.directory?
  end.join("nswtopo.cfg")

  @config, extra = [@path, @extra_path].map do |path|
    next Hash[] unless path&.file?
    config = YAML.load(path.read)
    Hash === config ? config : raise
  rescue YAML::Exception, RuntimeError
    log_warn "couldn't parse #{path} - ignoring"
    Hash[]
  end

  @merged = @config.deep_merge extra
end

#saveObject



68
69
70
71
# File 'lib/nswtopo/config.rb', line 68

def save
  @path.parent.mkpath
  @path.write @config.to_yaml
end

#store(*entries, key, value) ⇒ Object



40
41
42
43
44
45
# File 'lib/nswtopo/config.rb', line 40

def store(*entries, key, value)
  entries.inject(@config) do |config, entry|
    config[entry] ||= {}
    Hash === config[entry] ? config[entry] : raise("entry already taken: %s" % entry)
  end.store key, value
end