Class: Hiiro::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/hiiro/config.rb

Constant Summary collapse

BASE_DIR =
File.join(Dir.home, '.config/hiiro')
DATA_DIR =
File.join(Dir.home, '.local/share/hiiro')

Class Method Summary collapse

Class Method Details

.config_dir(subdir = nil) ⇒ Object



70
71
72
73
74
# File 'lib/hiiro/config.rb', line 70

def config_dir(subdir=nil)
  File.join(Dir.home, '.config/hiiro', *[subdir].compact).tap do |config_path|
    FileUtils.mkdir_p(config_path) unless Dir.exist?(config_path)
  end
end

.data_path(relpath = '') ⇒ Object



50
51
52
# File 'lib/hiiro/config.rb', line 50

def data_path(relpath='')
  File.join(DATA_DIR, relpath)
end

.load_yaml(relpath = 'config.yml', default: {}, permitted_classes: [Symbol]) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/hiiro/config.rb', line 20

def load_yaml(relpath = 'config.yml', default: {}, permitted_classes: [Symbol])
  file = path(relpath)
  return default unless File.exist?(file)

  YAML.safe_load_file(file, permitted_classes: permitted_classes) || default
rescue StandardError
  default
end

.open(file, dir: nil) ⇒ Object



9
10
11
12
13
14
# File 'lib/hiiro/config.rb', line 9

def open(file, dir: nil)
  dir_path = File.expand_path(dir || '~')
  full_path = File.expand_path(file, dir_path)
  Dir.chdir(dir_path)
  system(ENV['EDITOR'] || 'vim', full_path)
end

.path(relpath = '') ⇒ Object



16
17
18
# File 'lib/hiiro/config.rb', line 16

def path(relpath='')
  File.join(BASE_DIR, relpath)
end

.plugin_dirObject



66
67
68
# File 'lib/hiiro/config.rb', line 66

def plugin_dir
  config_dir('plugins')
end

.plugin_filesObject



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/hiiro/config.rb', line 54

def plugin_files
  user_files = Dir.glob(File.join(plugin_dir, '*.rb'))
  user_basenames = user_files.map { |f| File.basename(f) }

  gem_plugin_dir = File.join(File.expand_path('../..', __FILE__), 'plugins')
  gem_files = Dir.exist?(gem_plugin_dir) ? Dir.glob(File.join(gem_plugin_dir, '*.rb')) : []

  fallback_files = gem_files.reject { |f| user_basenames.include?(File.basename(f)) }

  user_files + fallback_files
end

.yaml_dig(relpath = 'config.yml', *keys, default: nil, permitted_classes: [Symbol]) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/hiiro/config.rb', line 29

def yaml_dig(relpath = 'config.yml', *keys, default: nil, permitted_classes: [Symbol])
  value = load_yaml(relpath, default: {}, permitted_classes: permitted_classes)

  keys.flatten.each do |key|
    return default unless value.is_a?(Hash)

    value =
      if value.key?(key)
        value[key]
      elsif value.key?(key.to_s)
        value[key.to_s]
      elsif key.respond_to?(:to_sym) && value.key?(key.to_sym)
        value[key.to_sym]
      else
        return default
      end
  end

  value.nil? ? default : value
end