Module: Config

Extended by:
Config
Included in:
Config
Defined in:
lib/nub/config.rb

Overview

Simple YAML configuration for an application. Uses singleton pattern for single source of truth

Constant Summary collapse

@@_yml =
nil

Class Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.pathObject

Returns the value of attribute path.



36
37
38
# File 'lib/nub/config.rb', line 36

def path
  @path
end

Instance Method Details

#[](key) ⇒ Object

Hash like getter



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

def [](key)
  return @@_yml[key]
end

#[]=(key, val) ⇒ Object

Hash like setter



71
72
73
# File 'lib/nub/config.rb', line 71

def []=(key, val)
  return @@_yml[key] = val
end

#exists?Boolean

Simple bool whether the config exists or not on disk

Returns:

  • (Boolean)


61
62
63
# File 'lib/nub/config.rb', line 61

def exists?
    return File.exists?(@path)
end

#get!(key) ⇒ Object

Get the given key and raise an error if it doesn’t exist



76
77
78
79
# File 'lib/nub/config.rb', line 76

def get!(key)
  Log.die("couldn't find '#{key}' in config") if !@@_yml.key?(key)
  return @@_yml[key]
end

#init(config) ⇒ Object

Singleton new alternate

Parameters:

  • config (String)

    name or path of the config file



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/nub/config.rb', line 41

def init(config)

  # Determine caller's file path to look for sidecar config
  caller_path = caller_locations(1, 1).first.path
  @path = File.expand_path(File.join(File.dirname(caller_path), config))
  if !File.exists?(@path)
    @path = "/home/#{User.name}/.config/#{config.split('/').first}"
  end

  # Open the config file or create in memory yml
  begin
    @@_yml = File.exists?(@path) ? YAML.load_file(@path) : {}
  rescue Exception => e
    Log.die(e)
  end

  return nil
end

#saveObject

Save the config file



82
83
84
85
# File 'lib/nub/config.rb', line 82

def save
  return unless @@_yml
  File.open(@path, 'w', 0600){|f| f.write(@@_yml.to_yaml)}
end