]> git.r.bdr.sh - rbdr/lyricli.rb/blob - lib/lyricli/configuration.rb
b90e772b1fa3bfc04ccae56ee8cc2a1b8b366b29
[rbdr/lyricli.rb] / lib / lyricli / configuration.rb
1 module Lyricli
2
3 # This class handles the configuration of Lyricli
4 class Configuration
5
6 # Defines the paths to the default and user configuration files
7 def initialize
8 @config_path = "~/.lyricli.conf"
9 @defaults_path = "defaults.json"
10 @config = nil
11 end
12
13 @@instance = Configuration.new
14
15 # Ensure this is only called once. Only use the instance class variable
16 # to access this method, as its constructor is private.
17 def self.instance
18 @@instance
19 end
20
21 # Access configuration properties, loads config if needed beforehand.
22 #
23 # @param [String] key the configuration key to access
24 # @return [String, Hash, Array] the value of the configuration key.
25 def [](key)
26 load_config unless @config
27 @config[key]
28 end
29
30 # Assigns a new value to a configuration key, loads config if needed and
31 # saves it after updating.
32 #
33 # @param [String] key the configuration key to set
34 # @param [Object] value the value for the configuration key, can be any
35 # object as long as it can be converted to JSON
36 def []=(key, value)
37 load_config unless @config
38 @config[key] = value
39 save_config
40 end
41
42 # Deletes a key from the configuration, loads config if needed and saves
43 # it after deleting.
44 #
45 # @param [String] key the key to delete
46 def delete(key)
47 load_config unless @config
48 @config.delete(key)
49 save_config
50 end
51
52 private_class_method :new
53
54 # Loads the configuration from the user file, attempts to create it from
55 # defaults if it's not present. sets the `@config` instance variable.
56 def load_config
57 path = File.expand_path(@config_path)
58
59 if File.exist?(path)
60 file = File.new(path, "r")
61 @config = MultiJson.decode(file.read)
62 else
63 load_default_config
64 end
65 end
66
67 # Serializes the `@config` Hash to JSON and saves it to a file.
68 def save_config
69 path = File.expand_path(@config_path)
70 file = File.new(path, "w")
71 file.print(MultiJson.encode(@config))
72 file.close
73 end
74
75 private
76
77 # Loads the default configuration from a JSON file
78 def load_default_config
79 # Load the default
80 path = File.join(::Lyricli.root, "config", @defaults_path)
81
82 if File.exists?(path)
83 file = File.new(path, "r")
84 @config = MultiJson.decode(file.read)
85 else
86 @config = {}
87 end
88 end
89 end
90 end