Class: AtCoderFriends::ConfigLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/at_coder_friends/config_loader.rb

Overview

loads configuration file from the specified directory.

Constant Summary collapse

DOTFILE =
'.at_coder_friends.yml'
ACF_HOME =
File.realpath(File.join(__dir__, '..', '..'))
DEFAULT_FILE =
File.join(ACF_HOME, 'config', 'default.yml')

Class Method Summary collapse

Class Method Details

.config_file_for(target_dir) ⇒ Object



22
23
24
# File 'lib/at_coder_friends/config_loader.rb', line 22

def config_file_for(target_dir)
  find_project_dotfile(target_dir) || DEFAULT_FILE
end

.default_configObject



41
42
43
# File 'lib/at_coder_friends/config_loader.rb', line 41

def default_config
  load_yaml(DEFAULT_FILE)
end

.find_file_upwards(filename, start_dir) ⇒ Object



30
31
32
33
34
35
# File 'lib/at_coder_friends/config_loader.rb', line 30

def find_file_upwards(filename, start_dir)
  Pathname.new(start_dir).expand_path.ascend do |dir|
    file = dir + filename
    return file.to_s if file.exist?
  end
end

.find_project_dotfile(target_dir) ⇒ Object



26
27
28
# File 'lib/at_coder_friends/config_loader.rb', line 26

def find_project_dotfile(target_dir)
  find_file_upwards(DOTFILE, target_dir)
end

.load_config(ctx) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/at_coder_friends/config_loader.rb', line 14

def load_config(ctx)
  path = config_file_for(ctx.path)
  config = load_yaml(path)
  return config if path == DEFAULT_FILE

  merge_with_default(config)
end

.load_yaml(path) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/at_coder_friends/config_loader.rb', line 56

def load_yaml(path)
  yaml = IO.read(path, encoding: Encoding::UTF_8)
  YAML.safe_load(yaml, [], [], false, path) || {}
rescue Errno::ENOENT
  raise ConfigNotFoundError,
        "Configuration file not found: #{path}"
end

.merge(base_hash, derived_hash) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/at_coder_friends/config_loader.rb', line 45

def merge(base_hash, derived_hash)
  res = base_hash.merge(derived_hash) do |_, base_val, derived_val|
    if base_val.is_a?(Hash) && derived_val.is_a?(Hash)
      merge(base_val, derived_val)
    else
      derived_val
    end
  end
  res
end

.merge_with_default(config) ⇒ Object



37
38
39
# File 'lib/at_coder_friends/config_loader.rb', line 37

def merge_with_default(config)
  merge(default_config, config)
end