The standard Ruby database interfaces assume you e connecting to a preexisting database, and that you already have access to this database. You want to create and administer MySQL databases from within Ruby.
Sam Ruby came up with an elegant solution to this problem. The mysql method defined below opens up a pipe to a MySQL client program and sends SQL input to it:
def mysql(opts, stream) IO.popen("mysql #{opts}", w) { |io| io.puts stream } end
You can use this technique to create, delete, and administer MySQL databases:
mysql -u root -p[password], <<-end drop database if exists website_db; create database website_db; grant all on website_db.* to #{`id -un`.strip}@localhost; end
This solution looks so elegant because of the <<-end declaration, which allows you to end the string the same way you end a code block.
One shortcoming of this solution is that the IO.popen call opens up a one-way communication with the MySQL client. This makes it difficult to call SQL commands and get the results back. If thats what you need, you can use IO.popen interactively; see Recipe 23.1.
Strings
Numbers
Date and Time
Arrays
Hashes
Files and Directories
Code Blocks and Iteration
Objects and Classes8
Modules and Namespaces
Reflection and Metaprogramming
XML and HTML
Graphics and Other File Formats
Databases and Persistence
Internet Services
Web Development Ruby on Rails
Web Services and Distributed Programming
Testing, Debugging, Optimizing, and Documenting
Packaging and Distributing Software
Automating Tasks with Rake
Multitasking and Multithreading
User Interface
Extending Ruby with Other Languages
System Administration