]> git.r.bdr.sh - rbdr/lyricli.rb/blame - lib/lyricli/configuration.rb
Fixes stuff for ruby 1.8 support
[rbdr/lyricli.rb] / lib / lyricli / configuration.rb
CommitLineData
823e558b 1module Lyricli
34d0bf15
BB
2
3 # This class handles the configuration of Lyricli
823e558b
BB
4 class Configuration
5
34d0bf15 6 # Defines the paths to the default and user configuration files
823e558b
BB
7 def initialize
8 @config_path = "~/.lyricli.conf"
9 @defaults_path = "defaults.json"
10 @config = nil
11 end
12
13 @@instance = Configuration.new
14
34d0bf15
BB
15 # Ensure this is only called once. Only use the instance class variable
16 # to access this method, as its constructor is private.
823e558b
BB
17 def self.instance
18 @@instance
19 end
20
34d0bf15
BB
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.
823e558b
BB
25 def [](key)
26 load_config unless @config
27 @config[key]
28 end
29
34d0bf15
BB
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
823e558b
BB
36 def []=(key, value)
37 load_config unless @config
38 @config[key] = value
39 save_config
40 end
41
34d0bf15
BB
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
4f3dbb13
BB
46 def delete(key)
47 load_config unless @config
48 @config.delete(key)
49 save_config
50 end
823e558b 51
4f3dbb13 52 private_class_method :new
823e558b 53
34d0bf15
BB
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.
823e558b 56 def load_config
4f3dbb13 57 path = File.expand_path(@config_path)
823e558b
BB
58
59 if File.exists?(path)
60 file = File.new(path, "r")
61 @config = MultiJson.decode(file.read)
62 else
4f3dbb13 63 load_default_config
823e558b
BB
64 end
65 end
66
34d0bf15 67 # Serializes the `@config` Hash to JSON and saves it to a file.
823e558b
BB
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
4f3dbb13
BB
74
75 private
76
34d0bf15 77 # Loads the default configuration from a JSON file
4f3dbb13
BB
78 def load_default_config
79 # Load the default
80 path_root = File.expand_path(File.dirname(__FILE__))
81 path = File.join(path_root, @defaults_path)
82
83 if File.exists?(path)
84 file = File.new(path, "r")
85 @config = MultiJson.decode(file.read)
86 else
87 @config = {}
88 end
89 end
823e558b
BB
90 end
91end