Class: Configuration

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

Defined Under Namespace

Modules: VERSION Classes: ConfFile, InvalidKey

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base, dir_tree = []) ⇒ Configuration

Returns a new instance of Configuration.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/configuration.rb', line 39

def initialize(base, dir_tree=[])
	# make it resistant against Dir.chdir
	@base  = File.expand_path(base).freeze
	@files = {}

	unless File.directory?(@base) && File.exist?("#@base/.configdir.yaml") then
		if File.file?(@base) then
			raise "Can't create directory #@base because of existing file #@base"
		end
		if File.exist?(@base) then
			raise "Directory #@base already exists and is not a configuration directory"
		end
	end
	unless File.exist?(@base) then
		FileUtils.mkdir_p(@base)
		File.open("#@base/.configdir.yaml", "w") { |fh|
			fh.write({
				:created  => Time.now,
				:modified => Time.now,
				:revision => 1,
			}.to_yaml)
		}
	end
	setup(dir_tree)
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



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

def base
  @base
end

Instance Method Details

#[](key) ⇒ Object



65
66
67
68
69
# File 'lib/configuration.rb', line 65

def [](key)
	file, key = split(key)
	return nil unless key_exist?(file, key)
	key ? @files[file][key] : @files[file]
end

#[]=(key, value) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/configuration.rb', line 71

def []=(key, value)
	file, key = split(key)
	load(file)
	if key then
		if Hash === @files[file] then
			@files[file][key] = value
		else
			@files[file] = {key => value}
		end
	else
		@files[file] = value
	end
	store(file)
	value
end

#delete(key) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
# File 'lib/configuration.rb', line 93

def delete(key)
	file, key = split(key)
	return nil unless key_exist?(file, key) and File.exist?(file)
	if key.empty? then
		File.delete(file)
	else
		load(file)
		@files[file].delete(key)
		store(file)
	end
end

#exist?(key) ⇒ Boolean Also known as: has_key?

Returns:

  • (Boolean)


87
88
89
90
# File 'lib/configuration.rb', line 87

def exist?(key)
	file, key = split(key)
	key_exist?(file, key)
end

#setup(dirs) ⇒ Object



105
106
107
# File 'lib/configuration.rb', line 105

def setup(dirs)
	FileUtils.mkdir_p(dirs.map { |dir| "#@base/#{dir}" })
end