Class: Ccp::Persistent::Tsv
- Inherits:
-
Dir
- Object
- Base
- Dir
- Ccp::Persistent::Tsv
show all
- Defined in:
- lib/ccp/persistent/tsv.rb
Instance Attribute Summary
Attributes inherited from Base
#serializer, #source
Class Method Summary
collapse
Instance Method Summary
collapse
Methods inherited from Dir
#exist?, #load, #path
Methods inherited from Base
#[], #exist?, #initialize, #load, #read, #read!, #save
Class Method Details
.ext ⇒ Object
4
5
6
|
# File 'lib/ccp/persistent/tsv.rb', line 4
def self.ext
"tsv"
end
|
Instance Method Details
#[]=(key, val) ⇒ Object
51
52
53
54
55
56
57
58
59
|
# File 'lib/ccp/persistent/tsv.rb', line 51
def []=(key, val)
case val
when Hash
tsv_path_for(key).open("w+"){|f| save_tsv(f, val)}
else
super
end
end
|
#files ⇒ Object
61
62
63
|
# File 'lib/ccp/persistent/tsv.rb', line 61
def files
Dir["#{path}/*.#{ext}"] + Dir["#{path}/*.#{ext}.#{self.class.ext}"]
end
|
#keys ⇒ Object
65
66
67
|
# File 'lib/ccp/persistent/tsv.rb', line 65
def keys
files.map{|i| File.basename(i).split(".").first}.sort
end
|
#load!(key) ⇒ Object
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/ccp/persistent/tsv.rb', line 40
def load!(key)
path = path_for(key)
if path.exist?
super
elsif (tsv = tsv_path_for(key)).exist?
load_tsv(tsv)
else
super
end
end
|
#load_tsv(path) ⇒ Object
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# File 'lib/ccp/persistent/tsv.rb', line 8
def load_tsv(path)
hash = {}
path.readlines.each_with_index do |line, i|
no = i+1
key, val = line.split(/\t/,2)
unless val
$stderr.puts "#{self.class}#load_tsv: value not found. key='#{key}' (line: #{no})"
next
end
obj = decode(val)
hash[key] = obj
end
return hash
end
|
#save_tsv(f, hash) ⇒ Object
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
# File 'lib/ccp/persistent/tsv.rb', line 24
def save_tsv(f, hash)
keys = hash.keys
keys =
case keys.first
when NilClass ; return
when Symbol ; keys
when /\A\d+\Z/; keys.sort_by(&:to_i)
when String ; keys.sort
else ; keys
end
keys.each do |key|
f.puts "%s\t%s\n" % [key, encode(hash[key])]
end
end
|
#truncate ⇒ Object
69
70
71
|
# File 'lib/ccp/persistent/tsv.rb', line 69
def truncate
files.each{|file| File.unlink(file)}
end
|
#tsv_path_for(key) ⇒ Object
73
74
75
|
# File 'lib/ccp/persistent/tsv.rb', line 73
def tsv_path_for(key)
Pathname(path_for(key).to_s + ".tsv")
end
|