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 # lets the user define a recovery procedure in case the Marshal
102 # deserialization fails, it might be manually recover data.
103 # NOTE: weird legacy stuff, used by markov plugin (WTH?)
104 attr_accessor :recovery
106 def initialize(filename)
107 debug 'init registry accessor for: ' + filename
109 @name = File.basename filename
115 def sub_registry(prefix)
116 path = File.join(@filename.gsub(/\.[^\/\.]+$/,''), prefix.to_s)
117 return self.class.new(path)
120 # creates the registry / subregistry folders
122 debug 'create folders for: ' + @filename
123 dirs = File.dirname(@filename).split("/")
124 dirs.length.times { |i|
125 dir = dirs[0,i+1].join("/")+"/"
126 unless File.exist?(dir)
132 # Will return true if the database file exists.
134 File.exists? @filename
137 # convert value to string form for storing in the registry
138 # defaults to Marshal.dump(val) but you can override this in your module's
139 # registry object to use any method you like.
140 # For example, if you always just handle strings use:
148 # restores object from string form, restore(store(val)) must return val.
149 # If you override store, you should override restore to reverse the
151 # For example, if you always just handle strings use:
158 rescue Exception => e
159 error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
161 if defined? @recovery and @recovery
163 return @recovery.call(val)
164 rescue Exception => ee
165 error _("marshal recovery failed, trying default")
173 # Returned instead of nil if key wasnt found.
174 def set_default (default)
179 @default && (@default.dup rescue @default)
182 # Opens the database (if not already open) for read/write access.
184 create_folders unless dbexists?
187 # Forces flush/sync the database on disk.
189 return unless @registry
193 # Should optimize/vacuum the database.
195 return unless @registry
199 # Closes the database.
201 return unless @registry
206 # lookup a key in the registry
208 if dbexists? and registry.has_key?(key.to_s)
209 return restore(registry[key.to_s])
215 # set a key in the registry
217 registry[key.to_s] = store(value)
222 return nil unless dbexists?
223 registry.each do |key|
224 block.call(key, self[key])
237 # like Hash#each_value
238 def each_value(&block)
239 self.each do |key, value|
244 # just like Hash#has_key?
246 return nil unless dbexists?
247 return registry.has_key?(key.to_s)
250 alias include? has_key?
251 alias member? has_key?
254 # just like Hash#has_value?
255 def has_value?(value)
256 return nil unless dbexists?
257 return registry.has_value?(store(value))
260 # just like Hash#index?
263 return k if v == value
268 # delete a key from the registry
270 return default unless dbexists?
271 return registry.delete(key.to_s)
274 # returns a list of your keys
276 return [] unless dbexists?
280 # just like Hash#has_both?
281 def has_both?(key, value)
282 return false unless dbexists?
283 registry.has_key?(key.to_s) and registry.has_value?(store(value))
286 # Return an array of all associations [key, value] in your namespace
288 return [] unless dbexists?
290 self.each {|key, value|
296 # Return an hash of all associations {key => value} in your namespace
298 return {} unless dbexists?
300 self.each {|key, value|
306 # empties the registry (restricted to your namespace)
308 return unless dbexists?
313 # returns an array of the values in your namespace of the registry
315 return [] unless dbexists?
323 # returns the number of keys in your registry namespace
325 return 0 unless dbexists?
330 # Returns all classes from the namespace that implement this interface
332 ObjectSpace.each_object(Class).select { |klass| klass < self }