File: settings.rb

package info (click to toggle)
screenruler 1.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 232 kB
  • sloc: ruby: 661; makefile: 52; sh: 2
file content (48 lines) | stat: -rw-r--r-- 838 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
require 'yaml'

class Settings
	def initialize
		@settings = {}
		@setting_callbacks = {}
	end

	def on_change(key, &proc)
		@setting_callbacks[key] ||= []
		@setting_callbacks[key] << proc
	end

	def load(path)
		File.open(path, 'r') { |file|
			load_settings_from_file(file)
		} rescue nil
		self
	end

	def save(path)
		File.open(path, 'w') { |file|
			save_settings_to_file(file)
		} rescue nil
		self
	end

	def [](key)
		@settings[key]
	end

	def []=(key, value)
		return if (@settings[key] && @settings[key] == value)
		@settings[key] = value
		@setting_callbacks[key].each { |proc| proc.call(value) } if @setting_callbacks[key]
	end

private

	def load_settings_from_file(file)
		settings = YAML.load(file)
		@settings = settings if settings.is_a? Hash
	end

	def save_settings_to_file(file)
		YAML.dump(@settings, file)
	end
end