Ruby script connect to Mysql2 using database.yml without Rails

I would like to connect to the mysql database using the mysql2 stone in a Ruby script, but without Rails or ActiveRecord, but at the same time reading the config / database.yml file so as not to expose the username and password directly inside the Ruby script. I can connect if I use ActiveRecord as follows:

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

But if I try the same trick for connecting Mysql2, I get an error message:

 client = Mysql2::Client.new(dbconfig['production']) 

The obviuosly syntax is different, I need something like:

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

But you do not need to specify the username and password directly inside the script.

so how can I grab all the data from config / database.yml and pass it to the Mysql2::Client.new() method?

Thanks.

Edit

I just wanted to clarify that in order to finally make it work, I slightly modified the answer received:

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

Just executing Mysql2::Client.new(config) will not work, because it will not take away the username and password.

+7
source share
3 answers

Any method that accepts a hash can be passed with the result of a YAML analysis.

You may have two problems:

The following code should work:

 config = YAML::load_file("config/database.yml")["development"] config["host"] = config["hostname"] client = Mysql2::Client.new(config) 
+11
source

My solution was similar to the accepted answer, except that my database.yml had erb fragments for references to environment variables:

 development: <<: *default database: <%= ENV['DEV_DB_NAME'] %> username: <%= ENV['DEV_DB_USER'] %> password: <%= ENV['DEV_DB_PASS'] %> 

So, first I upload via ERB:

 require 'erb' require 'mysql2' config = YAML.load(ERB.new( File.new("config/database.yml").read).result(binding))['development'] config["host"] = config["hostname"] client = Mysql2::Client.new(config) 

Thought it might help someone else, as this was the first search result I found. Thanks to the question and the accepted answer!

0
source

You can use sequel to do just that. The advantage of using a sequel is that you can use a good Ruby style to talk to your db. There are many examples on his documentaiton page.

-one
source

All Articles