Class: RBZK::CLI::Config
- Inherits:
-
Object
- Object
- RBZK::CLI::Config
- Defined in:
- lib/rbzk/cli/config.rb
Overview
Configuration handler for the CLI
Constant Summary collapse
- DEFAULT_CONFIG =
Default configuration values
{ 'ip' => '192.168.100.201', 'port' => 4370, 'timeout' => 30, 'password' => 0, 'verbose' => false, 'force_udp' => false, 'no_ping' => true, 'encoding' => 'UTF-8' }.freeze
Instance Method Summary collapse
-
#[](key) ⇒ Object
Get a configuration value.
-
#[]=(key, value) ⇒ Object
Set a configuration value.
-
#default_config_file ⇒ String
Get the default configuration file path.
-
#initialize(config_file = nil) ⇒ Config
constructor
Initialize a new configuration.
-
#load_config ⇒ Hash
Load the configuration from the file.
-
#save ⇒ Object
Save the configuration to the file.
-
#to_h ⇒ Hash
Get all configuration values.
Constructor Details
#initialize(config_file = nil) ⇒ Config
Initialize a new configuration
22 23 24 25 |
# File 'lib/rbzk/cli/config.rb', line 22 def initialize(config_file = nil) @config_file = config_file || default_config_file @config = load_config end |
Instance Method Details
#[](key) ⇒ Object
Get a configuration value
30 31 32 |
# File 'lib/rbzk/cli/config.rb', line 30 def [](key) @config[key.to_s] end |
#[]=(key, value) ⇒ Object
Set a configuration value
37 38 39 |
# File 'lib/rbzk/cli/config.rb', line 37 def []=(key, value) @config[key.to_s] = value end |
#default_config_file ⇒ String
Get the default configuration file path
54 55 56 57 58 59 60 61 62 |
# File 'lib/rbzk/cli/config.rb', line 54 def default_config_file if ENV['XDG_CONFIG_HOME'] File.join(ENV['XDG_CONFIG_HOME'], 'rbzk', 'config.yml') elsif ENV['HOME'] File.join(ENV['HOME'], '.config', 'rbzk', 'config.yml') else File.join(Dir.pwd, '.rbzk.yml') end end |
#load_config ⇒ Hash
Load the configuration from the file
66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/rbzk/cli/config.rb', line 66 def load_config if File.exist?(@config_file) begin config = YAML.load_file(@config_file) return DEFAULT_CONFIG.merge(config) if config.is_a?(Hash) rescue StandardError => e warn "Error loading configuration file: #{e.}" end end DEFAULT_CONFIG.dup end |
#save ⇒ Object
Save the configuration to the file
42 43 44 45 46 47 48 49 50 |
# File 'lib/rbzk/cli/config.rb', line 42 def save # Create the directory if it doesn't exist FileUtils.mkdir_p(File.dirname(@config_file)) # Save the configuration File.open(@config_file, 'w') do |f| f.write(YAML.dump(@config)) end end |
#to_h ⇒ Hash
Get all configuration values
80 81 82 |
# File 'lib/rbzk/cli/config.rb', line 80 def to_h @config.dup end |