Search code examples
rubymysql2puts

Preventing an Instance Method from Printing to Console


I am writing a simple Ruby script that utilizes the mysql2 gem.

In order to properly terminate a connection with the database and avoid the Too many connections error, I store my connection into the variable mysql like so:

mysql = Mysql2::Client.new(:host => hst, :username => usr, :password => pass, :database => db, :connect_timeout => 30)

and then I close the connection:

mysql.close

When this occurs, I get:

closed MySQL connection

in the console.

How can I implement the Instance Method #close found here without closed MySQL connection showing up in the terminal?


Solution

  • you can do this:

    def silence_stdout
      $stdout = File.new( '/dev/null', 'w' )
      yield
      ensure
      $stdout = STDOUT
    end
    

    and do the close with that method

    silence_stdout{mysql.close}