4 # :title: Registry: Persistent storage interface and factory
6 # This class provides persistent storage for plugins via a hash interface.
7 # The default mode is an object store, so you can store ruby objects and
8 # reference them with hash keys. This is because the default store/restore
9 # methods of the plugins' RegistryAccessor are calls to Marshal.dump and
14 # @registry[:blah] = blah
15 # then, even after the bot is shut down and disconnected, on the next run you
16 # can access the blah object as it was, with:
17 # blah = @registry[:blah]
18 # The registry can of course be used to store simple strings, fixnums, etc as
19 # well, and should be useful to store or cache plugin data or dynamic plugin
23 # in object store mode, don't make the mistake of treating it like a live
24 # object, e.g. (using the example above)
25 # @registry[:blah][:foo] = "flump"
26 # will NOT modify the object in the registry - remember that Registry#[]
27 # returns a Marshal.restore'd object, the object you just modified in place
28 # will disappear. You would need to:
29 # blah = @registry[:blah]
30 # blah[:foo] = "flump"
31 # @registry[:blah] = blah
33 # If you don't need to store objects, and strictly want a persistant hash of
34 # strings, you can override the store/restore methods to suit your needs, for
35 # example (in your plugin):
46 # Your plugins section of the registry is private, it has its own namespace
47 # (derived from the plugin's class name, so change it and lose your data).
48 # Calls to registry.each etc, will only iterate over your namespace.
55 # Dynamically loads the specified registry type library.
56 def initialize(format=nil)
57 @libpath = File.join(File.dirname(__FILE__), 'registry')
59 load File.join(@libpath, @format+'.rb') if format
62 # Returns a list of supported registry database formats.
64 Dir.glob(File.join(@libpath, '*.rb')).map do |name|
65 File.basename(name, File.extname(name))
69 # Creates a new Accessor object for the specified database filename.
70 def create(path, filename)
71 # The get_impl method will return a list of all the classes that
72 # implement the accessor interface, since we only ever load one
73 # (the configured one) accessor implementation, we can just assume
74 # it to be the correct accessor to use.
75 cls = AbstractAccessor.get_impl.first
76 db = cls.new(File.join(path, 'registry_' + @format, filename.downcase))
81 # Helper method that will return a list of supported registry formats.
83 @@formats ||= Registry.new.discover
86 # Will detect tokyocabinet registry location: ~/.rbot/registry/*.tdb
87 # and move it to its new location ~/.rbot/registry_tc/*.tdb
88 def migrate_registry_folder(path)
89 old_name = File.join(path, 'registry')
90 new_name = File.join(path, 'registry_tc')
91 if @format == 'tc' and File.exists?(old_name) and
92 not File.exists?(new_name) and
93 not Dir.glob(File.join(old_name, '*.tdb')).empty?
94 File.rename(old_name, new_name)
98 # Abstract database accessor (a hash-like interface).
99 class AbstractAccessor
101 attr_reader :filename
103 # lets the user define a recovery procedure in case the Marshal
104 # deserialization fails, it might be manually recover data.
105 # NOTE: weird legacy stuff, used by markov plugin (WTH?)
106 attr_accessor :recovery
108 def initialize(filename)
109 debug 'init registry accessor for: ' + filename
111 @name = File.basename filename
118 def sub_registry(prefix)
119 path = File.join(@filename.gsub(/\.[^\/\.]+$/,''), prefix.to_s)
120 @sub_registries[path] ||= self.class.new(path)
123 # creates the registry / subregistry folders
125 debug 'create folders for: ' + @filename
126 dirs = File.dirname(@filename).split("/")
127 dirs.length.times { |i|
128 dir = dirs[0,i+1].join("/")+"/"
129 unless File.exist?(dir)
135 # Will return true if the database file exists.
137 File.exists? @filename
140 # convert value to string form for storing in the registry
141 # defaults to Marshal.dump(val) but you can override this in your module's
142 # registry object to use any method you like.
143 # For example, if you always just handle strings use:
151 # restores object from string form, restore(store(val)) must return val.
152 # If you override store, you should override restore to reverse the
154 # For example, if you always just handle strings use:
161 rescue Exception => e
162 error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
164 if defined? @recovery and @recovery
166 return @recovery.call(val)
167 rescue Exception => ee
168 error _("marshal recovery failed, trying default")
176 # Returned instead of nil if key wasnt found.
177 def set_default (default)
182 @default && (@default.dup rescue @default)
185 # Opens the database (if not already open) for read/write access.
187 create_folders unless dbexists?
190 # Forces flush/sync the database on disk.
192 return unless @registry
193 # if not supported by the database, close/reopen:
198 # Should optimize/vacuum the database. (if supported)
202 # Closes the database.
204 return unless @registry
209 # lookup a key in the registry
211 if dbexists? and registry.has_key?(key.to_s)
212 return restore(registry[key.to_s])
218 # set a key in the registry
220 registry[key.to_s] = store(value)
225 return nil unless dbexists?
226 registry.each do |key, value|
227 block.call(key, restore(value))
240 # like Hash#each_value
241 def each_value(&block)
242 self.each do |key, value|
247 # just like Hash#has_key?
249 return nil unless dbexists?
250 return registry.has_key?(key.to_s)
253 alias include? has_key?
254 alias member? has_key?
257 # just like Hash#has_value?
258 def has_value?(value)
259 return nil unless dbexists?
260 return registry.has_value?(store(value))
263 # just like Hash#index?
266 return k if v == value
271 # delete a key from the registry
272 # returns the value in success, nil otherwise
274 return default unless dbexists?
275 value = registry.delete(key.to_s)
281 # returns a list of your keys
283 return [] unless dbexists?
287 # Return an array of all associations [key, value] in your namespace
289 return [] unless dbexists?
291 self.each {|key, value|
297 # Return an hash of all associations {key => value} in your namespace
299 return {} unless dbexists?
301 self.each {|key, value|
307 # empties the registry (restricted to your namespace)
309 return unless dbexists?
314 # returns an array of the values in your namespace of the registry
316 return [] unless dbexists?
324 # returns the number of keys in your registry namespace
326 return 0 unless dbexists?
331 # Returns all classes from the namespace that implement this interface
333 ObjectSpace.each_object(Class).select { |klass| klass < self }