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
117 def sub_registry(prefix)
118 path = File.join(@filename.gsub(/\.[^\/\.]+$/,''), prefix.to_s)
119 return self.class.new(path)
122 # creates the registry / subregistry folders
124 debug 'create folders for: ' + @filename
125 dirs = File.dirname(@filename).split("/")
126 dirs.length.times { |i|
127 dir = dirs[0,i+1].join("/")+"/"
128 unless File.exist?(dir)
134 # Will return true if the database file exists.
136 File.exists? @filename
139 # convert value to string form for storing in the registry
140 # defaults to Marshal.dump(val) but you can override this in your module's
141 # registry object to use any method you like.
142 # For example, if you always just handle strings use:
150 # restores object from string form, restore(store(val)) must return val.
151 # If you override store, you should override restore to reverse the
153 # For example, if you always just handle strings use:
160 rescue Exception => e
161 error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
163 if defined? @recovery and @recovery
165 return @recovery.call(val)
166 rescue Exception => ee
167 error _("marshal recovery failed, trying default")
175 # Returned instead of nil if key wasnt found.
176 def set_default (default)
181 @default && (@default.dup rescue @default)
184 # Opens the database (if not already open) for read/write access.
186 create_folders unless dbexists?
189 # Forces flush/sync the database on disk.
191 return unless @registry
192 # if not supported by the database, close/reopen:
197 # Should optimize/vacuum the database. (if supported)
201 # Closes the database.
203 return unless @registry
208 # lookup a key in the registry
210 if dbexists? and registry.has_key?(key.to_s)
211 return restore(registry[key.to_s])
217 # set a key in the registry
219 registry[key.to_s] = store(value)
224 return nil unless dbexists?
225 registry.each_key do |key|
226 block.call(key, self[key])
239 # like Hash#each_value
240 def each_value(&block)
241 self.each do |key, value|
246 # just like Hash#has_key?
248 return nil unless dbexists?
249 return registry.has_key?(key.to_s)
252 alias include? has_key?
253 alias member? has_key?
256 # just like Hash#has_value?
257 def has_value?(value)
258 return nil unless dbexists?
259 return registry.has_value?(store(value))
262 # just like Hash#index?
265 return k if v == value
270 # delete a key from the registry
272 return default unless dbexists?
273 value = registry.delete(key.to_s)
279 # returns a list of your keys
281 return [] unless dbexists?
285 # Return an array of all associations [key, value] in your namespace
287 return [] unless dbexists?
289 self.each {|key, value|
295 # Return an hash of all associations {key => value} in your namespace
297 return {} unless dbexists?
299 self.each {|key, value|
305 # empties the registry (restricted to your namespace)
307 return unless dbexists?
312 # returns an array of the values in your namespace of the registry
314 return [] unless dbexists?
322 # returns the number of keys in your registry namespace
324 return 0 unless dbexists?
329 # Returns all classes from the namespace that implement this interface
331 ObjectSpace.each_object(Class).select { |klass| klass < self }