]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blobdiff - lib/rbot/core/utils/extends.rb
Module\#define_structure method: define a new Struct only if doesn't exist already...
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
index bcea735b25a77e809c7a1a12fae22ab15421341f..1aa6d457a00e4f48fa7ad464128921cf6c0bfe32 100644 (file)
 # Please note that global symbols have to be prefixed by :: because this plugin
 # will be read into an anonymous module
 
+# Extensions to the Module class
+#
+class ::Module
+
+  # Many plugins define Struct objects to hold their data. On rescans, lots of
+  # warnings are echoed because of the redefinitions. Using this method solves
+  # the problem, by checking if the Struct already exists, and if it has the
+  # same attributes
+  #
+  def define_structure(name, *members)
+    sym = name.to_sym
+    if Struct.const_defined?(sym)
+      kl = Struct.const_get(sym)
+      if kl.new.members.map { |member| member.intern } == members.map
+        debug "Struct #{sym} previously defined, skipping"
+        const_set(sym, kl)
+        return
+      end
+    end
+    debug "Defining struct #{sym} with members #{members.inspect}"
+    const_set(sym, Struct.new(name.to_s, *members))
+  end
+end
+
 
 # Extensions to the Array class
 #