Module: Frecli::Settings

Defined in:
lib/frecli/settings.rb

Class Method Summary collapse

Class Method Details

.[](key) ⇒ Object



13
14
15
# File 'lib/frecli/settings.rb', line 13

def self.[](key)
  settings[key]
end

.compile_settings(root_path: '/') ⇒ Object

Merges .frecli files down from root dir. If .frecli is a dir, it will merge all files within. Relevant ENV vars will always take precedence.



20
21
22
23
24
25
26
27
28
29
# File 'lib/frecli/settings.rb', line 20

def self.compile_settings(root_path: '/')
  {}.tap do |settings|
    setting_filenames(root_path: root_path).each do |name|
      settings.merge!(
        Hash[YAML.load(File.open name).map { |(k, v)| [k.to_sym, v] }])
    end

    settings[:api_key] = ENV['FRECKLE_API_KEY'] if ENV.include?('FRECKLE_API_KEY')
  end
end

.join_paths(*paths) ⇒ Object



60
61
62
63
64
# File 'lib/frecli/settings.rb', line 60

def self.join_paths(*paths)
  separator = [*paths].first == '/' ? '' : '/'

  [*paths].join(separator)
end

.setting_filenames(root_path: '/') ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/frecli/settings.rb', line 31

def self.setting_filenames(root_path: '/')
  setting_paths(root_path: root_path).map do |path|
    filename = join_paths(path, '.frecli')

    next unless File.exist?(filename)

    if File.directory?(filename)
      Dir.glob(join_paths(filename, '*'))
    else
      filename
    end
  end.flatten.compact
end

.setting_paths(root_path: '/') ⇒ Object

Return all the paths from root_path to the current dir.

e.g.

‘/’, ‘/Users’, ‘/Users/isaac’, ‘/Users/isaac/project’


49
50
51
52
53
54
55
56
57
58
# File 'lib/frecli/settings.rb', line 49

def self.setting_paths(root_path: '/')
  Dir
    .getwd
    .sub(root_path, '/')
    .split('/')
    .reject(&:empty?)
    .inject([root_path]) do |path, wd|
    path << join_paths(path.last, wd)
  end
end

.settings(root_path: '/', reload: false) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/frecli/settings.rb', line 5

def self.settings(root_path: '/', reload: false)
  if reload || !@settings
    return (@settings = compile_settings(root_path: root_path))
  end

  @settings
end