I'm trying to write a rake task for loading data into my database. My plan is do something like
system "mysql -u foo -pbar database < backup.sql"
but I need to access the config/database.yml data for getting the user, pass and database info. The trick is I don't want to "parse" this fil开发者_运维百科e but to access this info in the same way tasks like rake db:reset do.
How can I do that?
This will work.
task :demo_using_db_config => :environment do
db_config = Rails.application.config.database_configuration[Rails.env]
system "mysql -u#{db_config['username']} -p#{db_config['password']} #{db_config['database']} < backup.sql"
end
Since this is environment specific, we want the task to depend on the :environment task.
Alternatively, if you are using ActiveRecord, you can get to this information like below:
abcs = ActiveRecord::Base.configurations
puts abcs[Rails.env]["username"]
puts abcs[Rails.env]["password"]
This works in rake tasks and elsewhere.
In Rails 3, from the console, you can type the following to see various database login credentials you defined in database.yml
config = Rails.application.config.database_configuration
In your rake file, you could specify something like this:
task :mysqlimport_table
db_config = Rails.application.config.database_configuration[Rails.env]
sh "mysqlimport -u#{db_config['username']} -p#{db_config['password']} #{db_config['database']} --default-character-set=utf8 --local <path_to_your_file>"
end
task :mysqlrun_sql_script
db_config = Rails.application.config.database_configuration[Rails.env]
sh "mysql -u#{db_config['username']} -p#{db_config['password']} -D#{db_config['database']} < <path_to_your_sql_file>"
end
Like this:
require 'yaml'
conf = YAML.load_file("path/to/database.yml")
精彩评论