Wrap all close() calls in "ensure" blocks and simplify DB connection-making.
[mailshears.git] / lib / common / agendav_plugin.rb
index 8eb73c19e029259426f9958e94f81af373ab0a14..49e7087d996ce2de850a01ec3c6d0a785b0ecd06 100644 (file)
@@ -14,13 +14,14 @@ module AgendavPlugin
   # @param cfg [Configuration] the configuration for this plugin.
   #
   def initialize(cfg)
-    @db_host = cfg.agendav_dbhost
-    @db_port = cfg.agendav_dbport
-    @db_opts = cfg.agendav_dbopts
-    @db_tty  = cfg.agendav_dbtty
-    @db_name = cfg.agendav_dbname
-    @db_user = cfg.agendav_dbuser
-    @db_pass = cfg.agendav_dbpass
+    @db_hash = {
+      :host     => cfg.agendav_dbhost,
+      :port     => cfg.agendav_dbport,
+      :options  => cfg.agendav_dbopts,
+      :tty      => cfg.agendav_dbtty,
+      :dbname   => cfg.agendav_dbname,
+      :user     => cfg.agendav_dbuser,
+      :password => cfg.agendav_dbpass }
   end
 
 
@@ -32,19 +33,21 @@ module AgendavPlugin
   def list_users()
     users = []
 
-    connection = PGconn.connect(@db_host, @db_port, @db_opts, @db_tty,
-                                @db_name, @db_user, @db_pass)
+    connection = PG::Connection.new(@db_hash)
 
     sql_query  = '(SELECT username FROM prefs)'
     sql_query += 'UNION'
     sql_query += '(SELECT user_from FROM shared);'
 
-    connection.query(sql_query) do |result|
-      users = result.field_values('username')
+    begin
+      connection.query(sql_query) do |result|
+        users = result.field_values('username')
+      end
+    ensure
+      # Make sure the connection gets closed even if the query explodes.
+      connection.close()
     end
 
-    connection.close()
-
     return users.map{ |u| User.new(u) }
   end