view raw
kakubei kakubei - 1 year ago 73
Ruby Question

Ruby script connect to Mysql2 using database.yml without Rails

I'd like to connect to a mysql database using the mysql2 gem in a Ruby script but without Rails 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:

dbconfig = YAML::load('config/database.yml'))
ActiveRecord::Base.establish_connection( dbconfig['production'] )

But if I try the same trick for the Mysql2 connection I get an error:

client =['production'])

Obviuosly the syntax is different, I need something like:

client = => "localhost", :username => "user", :password => 'password', :database => 'db', :socket => '/tmp/mysql.sock')

But don't want to expose the user name and password directly inside the script.

so how could I grab all the data from the config/database.yml and pass it to the



Just wanted to clarify that to finally get it to work I modified the accpeted answer a bit by doing this:

client = => dbconfig['hostname'], :username => dbconfig['username'], :password => dbconfig['password'], :database => dbconfig['database'], :socket => '/tmp/mysql.sock')

Simply doing
would not work because it would not pick up the username and password.


Any method that accept a hash can be fed with the result of a YAML parsing.

You may have two issue here :

The following code should work :

config = YAML::load_file("config/database.yml")["development"]
config["host"] = config["hostname"]

client =