Using ./script/runner
December 30th, 2006
Stop abusing the console!
Here is my confession: I’ve used the console in production mode to do some heavy lifting. I was shaking with nervousness though, because one weird typo or mixed up paste buffer could have meant disaster. You don’t have to though: In rails there is a pretty amazing tool, runner, that I only recently discovered the usefulness of.
Generally, it is a tool that lets you execute code within your rails app’s environment. For me, specifically, it helps me avoid abusing the console. Which is a hard habit for CLI-junkie like me to avoid. But I’m a programmer, damnit, I write programs. And I’m also not a DBA, I don’t trust myself to shoot from the hip with SQL. See, sometimes at work our beta-testing server’s database gets rebuilt. No biggie, but it is annoying because a few user settings that are in the database get lost. Until now I had been fixing this by tooling in the console. It is repepitive, it is tedious, and I typically forget how I have gone through the process by the time I finish it. Now I just write up my complex alterations in vim and run them with runner
#!/usr/bin/env script/runner
User.find_by_name($1).roles << Role.find_by_name('Super User')
And here is a little tip that you will help you debug your scripts: wrap everything in a transaction, then throw a breakpoint at the end of the transation so you can find out if your code did what you intended it to. Or, here is an even better tip, use breakpoint’s assert method.
Sorry, comments are closed for this article.