mysql.rake
Posted by Chad Humphries over 2 years ago / Source: http://errtheblog.com/post/33
The second part of our $ rake production mysql task (which we want to launch us into a shell connected to our production MySQL server) is the actual mysql task.

Here’s RAILS_ROOT/lib/tasks/mysql.rake, which we use to build and execute a mysql shell command using the configuration options set in database.yml. Using the config file ensures our mysql rake task is always synced up with our Rails application’s db settings.
def sh_mysql(config)
  returning '' do |mysql|
    mysql << mysql_command << ' '
    mysql << "-u#{config['username']} " if config['username']
    mysql << "-p#{config['password']} " if config['password']
    mysql << "-h#{config['host']} "     if config['host']
    mysql << "-P#{config['port']} "     if config['port']
    mysql << config['database']         if config['database']
  end
end

def mysql_command
  'mysql'
end

desc "Launch mysql shell.  Use with an environment task (e.g. rake production mysql)" 
task :mysql do
  system sh_mysql(YAML.load(open(File.join('config', 'database.yml')))[RAILS_ENV])
end
Language Ruby / Tagged with rake