title: Ruby script connect to Mysql2 using database.yml without Rails
body: <p>I'd like to connect to a mysql database using the mysql2 gem in a Ruby script but <strong>without Rails</strong> or ActiveRecord, yet reading the config/database.yml file so as not to expose the user name and password directly inside the Ruby script. I can connect if I use ActiveRecord like this:</p>
  
  <pre><code>dbconfig = YAML::load(File.open('config/database.yml'))
  ActiveRecord::Base.establish_connection( dbconfig['production'] )
  </code></pre>
  
  <p>But if I try the same trick for the Mysql2 connection I get an error:</p>
  
  <pre><code>client = Mysql2::Client.new(dbconfig['production'])
  </code></pre>
  
  <p>Obviuosly the syntax is different, I need something like:</p>
  
  <pre><code>client = Mysql2::Client.new(:host =&gt; "localhost", :username =&gt; "user", :password =&gt; 'password', :database =&gt; 'db', :socket =&gt; '/tmp/mysql.sock')
  </code></pre>
  
  <p>But don't want to expose the user name and password directly inside the script. </p>
  
  <p>so how could I grab all the data from the config/database.yml and pass it to the <code>Mysql2::Client.new()</code> method? </p>
  
  <p>Thanks.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>Just wanted to clarify that to finally get it to work I modified the accpeted answer a bit by doing this:</p>
  
  <pre><code>client = Mysql2::Client.new(:host =&gt; dbconfig['hostname'], :username =&gt; dbconfig['username'], :password =&gt; dbconfig['password'], :database =&gt; dbconfig['database'], :socket =&gt; '/tmp/mysql.sock')
  </code></pre>
  
  <p>Simply doing <code>Mysql2::Client.new(config)</code> would not work because it would not pick up the username and password.</p>