Tuesday, May 08, 2007

Prompting for Rails Database Password

from PragDave by Dave Thomas

Mike and I are running a Rails Studio in Denver. We were talking about database configuration, and an attendee asked "How can I make Rails prompt me for the database password, rather than hard code it into a configuration file?" It turns out that's easy to do, because the Rails configuration files are processed through the ERb templating system.

Here's what the production stanza looks like in the default database.yml file:

production:
adapter: mysql
database: events_production
username: root
password:

If we want to prompt at the console for a password, we can change it like this:


<%
def get_password
print "Password: "
`stty -echo`
STDIN.gets.chomp ensure `stty echo`
end
%>

production:
adapter: mysql
database: events_production
username: root
password: <%= get_password %>

Now, when Rails reads the configuration file, it gets to the password field and discovers it needs to run the get_password method. We define that method in the code block between <% and %>. This prompts for the password (with no echo--this only works on Unix boxes).

Does this really work in production: I don't know. It seems to, but I haven't tested it exhaustively.

No comments :