Search code examples
ruby-on-railsrubyactiverecordrakepg

Need to get usernames and passwords from database.yml file and pass into method in rake task


Currently, I am using the pg gem in my rails rake task which is perfect for what I want to do. I create a variable pg_conn and pass in the connection details to the PGconn.connect method. I just don't want to change this rake task everytime the database usernames/ passwords change. How can I pass in the login details from my yaml file to the pg_conn command. Take a look at my code below:

namespace :update_table do
  task :import => :environment do

$pg_conn = PGconn.connect(host =  "samsi-postgres-90s", port = 6433, options = '', tty ='',      dbname = "installs", login = "reports_m", password = "password")

my_query = "select * from all_tables"

   conn.query(my_query) do |raw_row|
     puts raw_row
   end

  end
end

Ideally, I would like to pass a hash of credential details to the pg_conn connection variable like so:

$pg_conn = PGconn.connect(yamlfile[:host], yamlfile[:port], '', '', yamlfile[:database], yamlfile[:username], yamlfile[:password])

How can I do this? Thank you for your help!


Solution

  • For Rails3, you can use Rails.configuration in your rake task:

      config   = Rails.configuration.database_configuration
      host     = config[Rails.env]["host"]
      database = config[Rails.env]["database"]
      username = config[Rails.env]["username"]
      password = config[Rails.env]["password"]
    

    Just make sure you inherit the environment in your rake task such as

    task :users => :environment do