I picked up Nikolai Krill’s CodeRunner a while back as a sort of scratch pad for writing code snippets. With support for a variety of languages, it looked like a handy tool for banging together scripts and experiments.
But I was let down a bit by one hope that didn’t pan out: a passing attempt at a kind of REPL for Objective-C. While Code Runner supports ObjC as a syntax, you can’t really use it to test your ideas against the frameworks.
Don’t let that get you down. Rails developers, it turns out, can really benefit from CodeRunner. Let me illustrate with an example: quite frequently I use the Rails console to figure out how to pull the data I want from my models. But the console is extremely limited: you can only enter one line at a time, and you can’t go back and modify your code without starting over again. To my knowledge, short of writing test controller actions, this was the only way to go about experimenting like this.
CodeRunner provides another way. Using Rails’ runner script, you can run arbitrary scripts against your app, loading up all its libraries and models. It’s the same power you get by loading the console. So I can compose scripts, edit them, and run them against my Rails app anytime. That screenshot heading this post is what I’m working on right now. It’s an experiment in a way of pulling a series of data from my models; when I’m done with this exercise I will have a hunk of code that I can drop right into a Rails method, and I’ll know it works. That’s hot.
Here’s how you do it.
- In CodeRunner, go to CodeRunner > Preferences.
- Choose the Languages tab.
- Hit the “+” sign to add a new Language.
- All you have to do is enter the command that CodeRunner will… er… run when you execute your script. It’s in this format:
~/Sites/cm-emailtrack/script/rails runner -e development $filename
Give the path to your Rails application, and leave that “$filename” — this is what CodeRunner uses to sub in the file you’re working with.
Ensure that you use the Ruby syntax lower in this window. You should end up with something like this:
Give it a descriptive name (remember, this is only going to work against a specific Rails app), and save it.
Boom! Your programming life just got a little easier. Have fun with it.