Class: RBZK::CLI::Config

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(config_file = nil) ⇒ Config

Initialize a new configuration

Parameters:

  • config_file (String) (defaults to: nil)

    Path to the configuration file



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

Parameters:

  • key (String, Symbol)

    Configuration key

Returns:

  • (Object)

    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

Parameters:

  • key (String, Symbol)

    Configuration key

  • value (Object)

    Configuration value



37
38
39
# File 'lib/rbzk/cli/config.rb', line 37

def []=(key, value)
  @config[key.to_s] = value
end

#default_config_fileString

Get the default configuration file path

Returns:

  • (String)

    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_configHash

Load the configuration from the file

Returns:

  • (Hash)

    Configuration values



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.message}"
    end
  end
  DEFAULT_CONFIG.dup
end

#saveObject

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_hHash

Get all configuration values

Returns:

  • (Hash)

    All configuration values



80
81
82
# File 'lib/rbzk/cli/config.rb', line 80

def to_h
  @config.dup
end