Module: Mysticonfig::Utils

Defined in:
lib/mysticonfig/utils.rb

Overview

Utilities

Class Method Summary collapse

Class Method Details

.generate_config_filenames(appname) ⇒ Object

Generate config filenames from given app name.



34
35
36
37
38
39
40
41
42
# File 'lib/mysticonfig/utils.rb', line 34

def self.generate_config_filenames(appname)
  return nil if appname.nil?

  {
    plain: ".#{appname}rc",
    json: ".#{appname}rc.json",
    yaml: [".#{appname}rc.yaml", ".#{appname}rc.yml"]
  }
end

.json_file?(file) ⇒ Boolean

Determine whether the given file is valid JSON file.

Returns:

  • (Boolean)


12
13
14
15
16
17
18
19
# File 'lib/mysticonfig/utils.rb', line 12

def self.json_file?(file)
  return false if file.nil?

  JSON.parse(File.read(file))
  true
rescue
  false
end

.load_auto(config_file) ⇒ Object

Load config file with automatic file type detection.



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/mysticonfig/utils.rb', line 62

def self.load_auto(config_file)
  return {} if config_file.nil? || !File.exist?(config_file)

  if json_file?(config_file)
    load_json(config_file)
  elsif yaml_file?(config_file)
    load_yaml(config_file)
  else
    {}
  end
end

.load_json(config_file) ⇒ Object

Load JSON config file.



46
47
48
49
50
# File 'lib/mysticonfig/utils.rb', line 46

def self.load_json(config_file)
  return {} if config_file.nil? || !File.exist?(config_file)

  JSON.parse(File.read(config_file))
end

.load_yaml(config_file) ⇒ Object

Load YAML config file.



54
55
56
57
58
# File 'lib/mysticonfig/utils.rb', line 54

def self.load_yaml(config_file)
  return {} if config_file.nil? || !File.exist?(config_file)

  YAML.safe_load(File.read(config_file))
end

.lookup_file(config_file, dir = Dir.pwd) ⇒ Object

Look up for an existent config file.



76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/mysticonfig/utils.rb', line 76

def self.lookup_file(config_file, dir = Dir.pwd)
  dir = File.realpath dir

  # Stop on home directory or root directory.
  home_path = File.expand_path '~'
  while (dir != home_path) && (dir != '/')
    current_filepath = File.expand_path(config_file, dir)
    return current_filepath if File.exist?(current_filepath)

    dir = File.realpath('..', dir) # Traverse up
  end

  nil
end

.yaml_file?(file) ⇒ Boolean

Determine whether the given file is valid YAML file.

Returns:

  • (Boolean)


23
24
25
26
27
28
29
30
# File 'lib/mysticonfig/utils.rb', line 23

def self.yaml_file?(file)
  return false if file.nil? || json_file?(file)

  result = YAML.safe_load(File.read(file))
  result.is_a?(Hash)
rescue
  false
end