Class: Lyricli::Configuration

Inherits:
Object
  • Object
show all
Defined in:
lib/lyricli/configuration.rb

Overview

This class handles the configuration of Lyricli

Constant Summary

@@instance =
Configuration.new

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Configuration) initialize

Defines the paths to the default and user configuration files



7
8
9
10
11
# File 'lib/lyricli/configuration.rb', line 7

def initialize
  @config_path = "~/.lyricli.conf"
  @defaults_path = "defaults.json"
  @config = nil
end

Class Method Details

+ (Object) instance

Ensure this is only called once. Only use the instance class variable to access this method, as its constructor is private.



17
18
19
# File 'lib/lyricli/configuration.rb', line 17

def self.instance
  @@instance
end

Instance Method Details

- (String, ...) [](key)

Access configuration properties, loads config if needed beforehand.

Parameters:

  • key (String)

    the configuration key to access

Returns:

  • (String, Hash, Array)

    the value of the configuration key.



25
26
27
28
# File 'lib/lyricli/configuration.rb', line 25

def [](key)
  load_config unless @config
  @config[key]
end

- (Object) []=(key, value)

Assigns a new value to a configuration key, loads config if needed and saves it after updating.

Parameters:

  • key (String)

    the configuration key to set

  • value (Object)

    the value for the configuration key, can be any object as long as it can be converted to JSON



36
37
38
39
40
# File 'lib/lyricli/configuration.rb', line 36

def []=(key, value)
  load_config unless @config
  @config[key] = value
  save_config
end

- (Object) delete(key)

Deletes a key from the configuration, loads config if needed and saves it after deleting.

Parameters:

  • key (String)

    the key to delete



46
47
48
49
50
# File 'lib/lyricli/configuration.rb', line 46

def delete(key)
  load_config unless @config
  @config.delete(key)
  save_config
end

- (Object) load_config

Loads the configuration from the user file, attempts to create it from defaults if it’s not present. sets the `@config` instance variable.



56
57
58
59
60
61
62
63
64
65
# File 'lib/lyricli/configuration.rb', line 56

def load_config
  path = File.expand_path(@config_path)

  if File.exists?(path)
    file = File.new(path, "r")
    @config = MultiJson.decode(file.read)
  else
    load_default_config
  end
end

- (Object) save_config

Serializes the `@config` Hash to JSON and saves it to a file.



68
69
70
71
72
73
# File 'lib/lyricli/configuration.rb', line 68

def save_config
  path = File.expand_path(@config_path)
  file = File.new(path, "w")
  file.print(MultiJson.encode(@config))
  file.close
end