Class: PersistentHash

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

Instance Method Summary collapse

Constructor Details

#initialize(file_path, commit_interval = 1) ⇒ PersistentHash

Returns a new instance of PersistentHash.



2
3
4
5
6
7
8
9
10
11
# File 'lib/meimei/persistent_hash.rb', line 2

def initialize(file_path, commit_interval = 1)
	@commit_interval = commit_interval
	@commit_count = 0
	@file_path = file_path
	restore!
	unless @hash.is_a?(Hash)
		@hash = {}
		commit!
	end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *params, &block) ⇒ Object



40
41
42
# File 'lib/meimei/persistent_hash.rb', line 40

def method_missing(name, *params, &block)
	@hash.send(name, *params, &block)
end

Instance Method Details

#[]=(key, value) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/meimei/persistent_hash.rb', line 31

def []=(key, value)
	@hash[key] = value
	@commit_count += 1
	if @commit_count >= @commit_interval
		@commit_count = 0
		commit!
	end
end

#commit!Object



25
26
27
28
29
# File 'lib/meimei/persistent_hash.rb', line 25

def commit!
	File.open(@file_path, File::WRONLY | File::CREAT) do |f|
		Marshal.dump(@hash, f)
	end
end

#restore!Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/meimei/persistent_hash.rb', line 13

def restore!
	if File.exist?(@file_path)
		mode = File::RDONLY
	else
		return
	end

	File.open(@file_path, mode) do |f|
		@hash = Marshal.restore(f)
	end
end