Created
October 28, 2016 02:55
-
-
Save muZk/9651df1bbf739325e7d8ab8b6ffe8f4b to your computer and use it in GitHub Desktop.
Rails rake task for creating a mysql user and password
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :db do | |
task 'mysql:create' do | |
puts '== Database Configuration ==' | |
app_name = Rails.application.class.parent_name.underscore | |
database_name = ENV['database'] || "#{app_name}_db_#{Rails.env}" | |
database_user_name = ENV['database_user'] || "#{app_name}_user_#{Rails.env}" | |
database_user_password = ENV['database_password'] || '' | |
puts " Database: #{database_name}" | |
puts " User: #{database_user_name}" | |
puts " Password: #{database_user_password}" | |
puts '== Creating SQL script ==' | |
Tempfile.open %w(mysql_config .sql) do |f| | |
f.print <<-SQL | |
CREATE USER '#{database_user_name}'@'localhost' IDENTIFIED BY '#{database_user_password}'; | |
GRANT ALL PRIVILEGES ON #{database_name}.* TO '#{database_user_name}'@'localhost'; | |
FLUSH PRIVILEGES; | |
SQL | |
f.flush | |
puts '== Running SQL script ==' | |
cmd = "mysql -u root -p < #{f.path}" | |
system(cmd) || abort("\n== Command #{cmd} failed ==") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment