Class: Ccp::Persistent::File

Inherits:
Base
  • Object
show all
Defined in:
lib/ccp/persistent/file.rb

Instance Attribute Summary

Attributes inherited from Base

#serializer, #source

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#[], #save

Constructor Details

#initialize(source, serializer) ⇒ File

Returns a new instance of File.



8
9
10
11
# File 'lib/ccp/persistent/file.rb', line 8

def initialize(source, serializer)
  @serializer = Ccp::Serializers.lookup(serializer)
  @source     = File.extname(source) == ".#{ext}" ? source : "#{source}.#{ext}"
end

Class Method Details

.extObject



4
5
6
# File 'lib/ccp/persistent/file.rb', line 4

def self.ext
  ""
end

Instance Method Details

#[]=(key, val) ⇒ Object



32
33
34
35
36
# File 'lib/ccp/persistent/file.rb', line 32

def []=(key, val)
  hash = read
  hash[key.to_s] = val
  raw_write(encode(hash))
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/ccp/persistent/file.rb', line 13

def exist?(key)
  read.has_key?(key.to_s)
end

#keysObject



38
39
40
# File 'lib/ccp/persistent/file.rb', line 38

def keys
  read!.keys.sort
end

#load(key) ⇒ Object



26
27
28
29
30
# File 'lib/ccp/persistent/file.rb', line 26

def load(key)
  load!(key)
rescue Ccp::Persistent::NotFound
  nil
end

#load!(key) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/ccp/persistent/file.rb', line 17

def load!(key)
  hash = read
  if hash.has_key?(key.to_s)
    hash[key.to_s]
  else
    raise Ccp::Persistent::NotFound, key.to_s
  end
end

#pathObject



46
47
48
# File 'lib/ccp/persistent/file.rb', line 46

def path
  @path ||= Pathname(@source)
end

#readObject



50
51
52
53
54
# File 'lib/ccp/persistent/file.rb', line 50

def read
  read!
rescue Ccp::Persistent::NotFound
  {}
end

#read!Object



56
57
58
59
# File 'lib/ccp/persistent/file.rb', line 56

def read!
  path.exist? or raise Ccp::Persistent::NotFound, path.to_s
  decode(path.open("rb").read{}).must(Hash)
end

#truncateObject



42
43
44
# File 'lib/ccp/persistent/file.rb', line 42

def truncate
  File.unlink(path.to_s)
end