Matthew Bellantoni

A Rails Rake Task to Create a Database User

Every time I start to mess around with a new Ruby on Rails project, I've forgotten how to set up a user on MySQL.  So, I wrote this Rake task.

It takes the username and password out of the database.yml file for the given Ruby environment and creates that user with that password for you.  I've only tried this with MySQL (and you'll notice that the exec is called "mysql5" on my Mac OS X 10.6 machine.)

Now I have to remember very little.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  namespace :db do
  
    desc 'Setup required user account.'
    task :create_user => :load_config do
      create_user(ActiveRecord::Base.configurations[Rails.env])
    end
    
    def create_user(config)
      case config['adapter']
      when /mysql/
        username = config['username']
        password = config['password']
        
        sql_command = "\"CREATE USER '#{username}'@'localhost' " +
        "IDENTIFIED BY '#{password}';" +
        "GRANT ALL ON *.* TO '#{username}'@'localhost';\""
        
        system("echo #{sql_command} | mysql5 -u root -p")
        
      when /sqlite/
        # There's nothing to do!
      else
        # Pardon my laziness!
        raise "#{config['adapter']} isn't supported."
      end
    end
  end

(Yes, I know there's SQLite, but I don't wanna use that!)


My First Appearance on the Internet

I thought I'd kick off my latest contribution to the Internet by trying to dig up my earliest.   Near as I can tell, it's a post to the alt.angst Usenet newsgroup (now subsumed by Google Groups) in a post entitled "Ignore This" dated July 26, 1993.

Here follows the post in its entirety.

It just won't finish itself...

matthew

I have no idea to what it was that wouldn't finish!