Module: Config
Overview
Simple YAML configuration for an application. Uses singleton pattern for single source of truth
Constant Summary collapse
- @@yml =
Defaults
{}
- @@path =
""
Instance Method Summary collapse
-
#[](key) ⇒ Object
Hash like getter.
-
#[]=(key, val) ⇒ Object
Hash like setter.
-
#exists? ⇒ Boolean
Simple bool whether the config exists or not on disk.
-
#get!(key) ⇒ Object
Get the given key and raise an error if it doesn’t exist.
-
#init(config) ⇒ Object
Singleton new alternate.
-
#reset ⇒ Object
Set back to defaults read for init again.
-
#save ⇒ Object
Save the config file.
Instance Method Details
#[](key) ⇒ Object
Hash like getter
76 77 78 |
# File 'lib/nub/config.rb', line 76 def [](key) return @@yml[key] end |
#[]=(key, val) ⇒ Object
Hash like setter
81 82 83 |
# File 'lib/nub/config.rb', line 81 def []=(key, val) return @@yml[key] = val end |
#exists? ⇒ Boolean
Simple bool whether the config exists or not on disk
71 72 73 |
# File 'lib/nub/config.rb', line 71 def exists? return File.exists?(@@path) end |
#get!(key) ⇒ Object
Get the given key and raise an error if it doesn’t exist
86 87 88 89 |
# File 'lib/nub/config.rb', line 86 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
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# 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.(File.join(File.dirname(caller_path), config)) if !File.exists?(path) path = "/home/#{User.name}/.config/#{config.split('/').first}" end # Don't reload if its already been done return Config if @@path == path @@path = path # 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 Config end |
#reset ⇒ Object
Set back to defaults read for init again
65 66 67 68 |
# File 'lib/nub/config.rb', line 65 def reset self.yml = {} self.path = "" end |
#save ⇒ Object
Save the config file
92 93 94 95 |
# File 'lib/nub/config.rb', line 92 def save return unless @@yml File.open(@@path, 'w', 0600){|f| f.write(@@yml.to_yaml)} end |