Module: Config
Overview
Simple YAML configuration for an application. Uses singleton pattern for single source of truth
Constant Summary collapse
- @@_yml =
nil
Class Attribute Summary collapse
-
.path ⇒ Object
Returns the value of attribute 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.
-
#save ⇒ Object
Save the config file.
Class Attribute Details
.path ⇒ Object
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
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
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.(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 |
#save ⇒ Object
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 |