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.
kakubei
source share