Module: Kerbi::ConfigFile

Defined in:
lib/config/config_file.rb

Constant Summary collapse

DIR_NAME =
".kerbi"
FILE_NAME =
"config.json"

Class Method Summary collapse

Class Method Details

.create_file_if_missingObject



16
17
18
19
20
21
22
23
# File 'lib/config/config_file.rb', line 16

def self.create_file_if_missing
  unless File.exists?(file_path)
    unless Dir.exists?(dir_path)
      Dir.mkdir(dir_path)
    end
    write({}, skip_check: true)
  end
end

.dir_pathObject



12
13
14
# File 'lib/config/config_file.rb', line 12

def self.dir_path
  "#{Dir.home}/#{DIR_NAME}"
end

.file_pathObject



8
9
10
# File 'lib/config/config_file.rb', line 8

def self.file_path
  "#{Dir.home}/#{DIR_NAME}/#{FILE_NAME}"
end


57
58
59
# File 'lib/config/config_file.rb', line 57

def self.legal_keys
  Kerbi::Consts::OptionKeys::LEGAL_CONFIG_FILE_KEYS
end

.patch(config) ⇒ Object

Parameters:

  • config (Hash)


46
47
48
49
50
# File 'lib/config/config_file.rb', line 46

def self.patch(config)
  existing_config = read
  new_config = existing_config.merge(config)
  write(new_config)
end

.readHash{Symbol, String}

Returns:

  • (Hash{Symbol, String})


26
27
28
29
30
31
32
33
34
35
36
# File 'lib/config/config_file.rb', line 26

def self.read
  begin
    create_file_if_missing
    contents = File.read(file_path)
    dict = JSON.parse(contents)
    dict.slice(*legal_keys)
  rescue StandardError => e
    $stderr.puts "[WARN] failed to read config #{file_path} (#{e})"
    {}
  end
end

.resetObject



52
53
54
55
# File 'lib/config/config_file.rb', line 52

def self.reset
  create_file_if_missing
  write({})
end

.write(config, skip_check: false) ⇒ Object

Parameters:

  • config (Hash)


39
40
41
42
43
# File 'lib/config/config_file.rb', line 39

def self.write(config, skip_check: false)
  create_file_if_missing unless skip_check
  config = config.deep_dup.stringify_keys.slice(*legal_keys)
  File.write(file_path, JSON.dump(config))
end