module Mysticonfig::Utils

Utilities

Public Class Methods

generate_config_filenames(appname) click to toggle source

Generate config filenames from given app name.

# 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) click to toggle source

Determine whether the given file is valid JSON file.

# 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) click to toggle source

Load config file with automatic file type detection.

# 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) click to toggle source

Load JSON config file.

# 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) click to toggle source

Load YAML config file.

# 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) click to toggle source

Look up for an existent config file.

# 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) click to toggle source

Determine whether the given file is valid YAML file.

# 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