File: persistent.rb

package info (click to toggle)
libnora-ruby 1%3A0.0.20041021-4
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 408 kB
  • ctags: 726
  • sloc: ruby: 5,186; ansic: 669; makefile: 248; sql: 10
file content (93 lines) | stat: -rwxr-xr-x 2,139 bytes parent folder | download | duplicates (5)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Web::Persistent
# Copyright(c) 2002 MoonWolf <moonwolf@moonwolf.com>
require 'web/persistent/idgen'
require 'web/persistent/serialize'
require 'web/persistent/store'
require 'web/persistent/lock'

module Web
  class Persistent
    def initialize(id=nil, options={})
      @idgen     = options[:idgen]     || Web::Persistent::IDgen::Default
      @iggen_opt = options[:idgen_opt] || {}
      if id
        @persistent_id = id
      else
        @persistent_id = @idgen::unique_id
      end
      
      @serializer     = options[:serializer]     || Web::Persistent::Serialize::Marshal
      @serializer_opt = options[:serializer_opt] || {}
      
      @storeman       = options[:storeman]       || Web::Persistent::Store::GDBM
      @storeman_opt   = options[:storeman_opt]   || {:dir=>'/tmp',:prefix=>'gdbm'}
      @store          = @storeman.new(@persistent_id, @storeman_opt)
      
      @lockman        = options[:lockman]        || Web::Persistent::Lock::Flock
      @lockman_opt    = options[:lockman_opt]    || {:dir=>'/tmp',:prefix=>'lock'}
      @lock           = @lockman.new(@persistent_id, @lockman_opt)
      
      @in_transaction = false
    end

    def close
      @store.close
    end

    def persistent_id
      @persistent_id
    end

    def in_transaction
      raise "not in transaction" unless @in_transaction
    end
    
    def transaction
      raise "nested transaction" if @in_transaction
      @in_transaction = true
      
      @lock.lock
      @store.open
      
      yield
      
      @store.close
      @lock.unlock
      
      @in_transaction = false
    end
    
    
    def [](key)
      in_transaction
      str = @store[key]
      if str
        value = @serializer.restore(str)
      else
        nil
      end
    end

    def []=(key,obj)
      in_transaction
      str = @serializer.dump(obj)
      @store[key] = str
    end
    
    def has_key?(key)
      in_transaction
      @store.has_key?(key)
    end
    
    def delete(key)
      in_transaction
      @store.delete(key)
    end
    
    def keys
      in_transaction
      @store.keys
    end
    
  end # Persistent
end # Web