Secrets of the Rails Console Ninjas
Have you ever used the Rails console? I’d love to see a show of hands (or comments, really). If notboy, are you in for a treat.
The console lets you fiddle with parts of your Rails appmodels especiallyin a real-time environment, instead of waiting for page reloads and clicking on links and using object dumps or breakpoints to try and get a picture of what’s going on behind the scenes.
<span id="more-13421"></span>
Into JavaScript? Have I got good news for you!
If you’re interested in JavaScript-driven web apps, snazzy visual fx, and generally confusing people into thinking your site is Flash—but oh-so-much better—you should buy our JavaScript Performance Rocks! book while it’s still in beta. Written by Thomas Fuchs, the creator of Scriptaculous, and yours truly, the maker of funny jokes and shiny graphics.
We cover everything from The Most Ridiculous Performance Fix Ever (and it is ridiculous), to serving strategies, DOM diets, loop unrolling (for those really extreme cases), how to play nice with the garbage collector, and everything in between. And it comes with our custom profiling tool, The DOM Monster, which analyzes your pages and suggests fixes. This package is only $24 right now but will be $29 as soon as it’s done, in mid-June 2009… but if you snag your copy today, you get the final version by email just as soon as it’s ready and save a noteworthy 5 bux! You can’t lose.
Have you ever used the Rails console? I’d love to see a show of hands (or comments, really). If notboy, are you in for a treat.
The console lets you fiddle with parts of your Rails appmodels especiallyin a real-time environment, instead of waiting for page reloads and clicking on links and using object dumps or breakpoints to try and get a picture of what’s going on behind the scenes.
I personally hadn’t used the console much at all until I watched Ezra Zygmuntowicz doing his thang at Workshop for Good; now, I know I can live without it, but it is an impoverished existence to be sure, full of page reloading and hair pulling and screams of primal rage.
What’s the big deal?
You want the big deal? You can’t handle the big deerr. Sorry. I think I just got a little bit, ahem, carried away. Not using the console results in RSI from constant page reloading, self-inflicted hair loss, and a distinct rise in cortisol.
But on the positive side of things, the console lets you do things like this without faking out your controller and hitting reload a bunch of times:
>> @george = Person.find_by_name('George')
>> @bob = Person.find_by_name('Bob')
>> @bob.friends << @george
Now, I’ve left out the return values of all these actions, for readability’s sake. But every time you perform a line of code in the console, you’ll get back the resultit’ll show you how the object has changed, or whether an action resulted in true or false, and so on. You can inspect and manipulate stuff, live, without writing the code in a controller, saving the file, reloading your browser, etc., etc., ad nauseum.
It’s not only a time saver, it’s a much better development practice.
Starting the console (a do run run run…)
When you create a new Rails app (project directory), it comes complete with a script
directory, which includes, among other things, the generate
script which can create controllers, models, and other files for you (including scaffolding).
But we’re not talking about generate
today, we’re talking about the console. As in, script/console
. Which is not only its name, but how you run it. Take up your terminal or command-line, pop into your Rails app’s root directory (aka RAILS_ROOT
) and take a whack at the following:
$ script/console
Ding! You will be rewarded with something like the following:
Loading development environment.
>>
The first line will tell you which Rails environment your console is running inand yes, you can specify it (see below). The second line is your promptfollowed by a fat little text insert bar which, depending on your OS and shell configuration, might be blinking, or might not. But either way, it’s beckoning to you, “Play with me!” (the little flirt).
Specifying console environment
By default, script/console
will load itself using your development production environmentunless your environment variables specify otherwise.
You can also tell the console at run-time which environment to start in, simply by tacking the environment name onto your command:
$ script/console production
$ script/console test
$ script/console development
Using the console
When you’re in the console, you have access to all your Rails app’s models and other classes, in addition to all the goodies that the Ruby standard lib offers.
Seeing the return values
Whenever you enter an expression into the console, the result of that expression will always be displayed, preceded by the =>
marker:
>> "monkey" + "ball"
=> "monkeyball"
>> 6 * 7
=> 42
In the case of complex objects, this can be a messy thing indeed:
>> @bob = User.new({:name => "Bob", :job => "Test Dummy"})
=> #<User:0x2645874 @new_record=true, @attributes={"name"=>"Bob", "job"=>"Test Dummy"}>
Entering code
You can enter code into the console just like you would in a file, or another terminal-based application:
>> ['foo','bar','bat'].each { |word| puts word }
foo
bar
bat
=> ["foo", "bar", "bat"]
Or you can enter code involving multiple lines:
>> ['foo','bar','bat'].each do |word|
?> puts word
>> end
foo
bar
bat
=> ["foo", "bar", "bat"]
The ?>
indicates that you’re inside a block of code which will need to be terminated one way or another.
Getting out of a block of code
If you’re in an indented block of code (e.g., something that should be terminated with end
) and want to escape without finishing, you can use ctrl + c
to get back to the top level. The current expression will be ignored and not run.
Accessing the last return value
Oops! You wrote some fancy code in the console and hit Enter
but you forgot to actually store it in a variable. But all is not lost, and you don’t have to run the code again. The console provides a magic variable ( _
) for your use, which will automatically give you the last return value the console saw:
>> "monkey" + "ball"
=> "monkeyball"
>> string = _
=> "monkeyball"
>> string
=> "monkeyball"
You can perform operations directly on _
, but remember that that will modify the contents of _
as soon as it’s run.
Running the same command again
Just like in most terminal applications, you can access your command history using your keyboard’s up and down arrows. Up goes backwards in time… down, of course, goes forward (and you can only go forward when you’re already backwardso much for irb
being the secret to time travel. sigh!).
Examining objects
There are a couple ways to check out objects in the console. The first, of course, is to just make use of the way it shows the inspect
method on everything:
>> @bob
=> #<User:0x2645874 @new_record=true, @attributes={"name"=>"Bob", "job"=>"Test Dummy"}>
But there’s a much more readable alternative:
>> puts @bob.to_yaml
--- !ruby/object:User
attributes:
name: Bob
job: Test Dummy
new_record: true
=> nil
But wait! There’s more! Or, less, really, because there’s a much shorter way:
>> y @bob
YAMLicious.
Including things
You can require libraries in the console just like you can in a file containing Ruby code:
require 'mylib'
You may have to provide a file path if the file is not in one of the places that the console looks.
Reloading the console
When you change your models and such and need to see those changes reflected in your Rails app in a web browser you just hit Reload
. In dev mode, the Rails app loads all the files anew every single time a page is requested. The same is true for the consolebut it loads the files anew every time you start the console, instead of per page request.
To avoid having to quit and reopen the console every time you change your application’s code, simply type the follow command:
>> Dispatcher.reset_application!
Or, better yet:
>> reload!
This is what you’ll see:
>> reload!
Reloading...
=> [ApplicationController, User]
All your models and suchlike will show up in this array, showing you what is being loaded. The best part is, you won’t have to refetch your objectsthey’ll be updated.
Exiting the console
Just type exit
. Yep, it’s that easy.
What to do with it
The console is ideal for working on your models, for such tasks as:
- working out kinks in your relationship design
- figuring out if your models model your data in a way that feels right when it comes down to brass tacks (e.g. writing real code)
- examine your model objects, live, to help ferret out problems
It’s also a great way to become more comfortable writing Rails code off the cuff… it’s easier to practice if the process isn’t as tedious.
A note for the cowboy coder in all of us: The console is not a replacement for writing unit tests. It’s a complementary technique. Write those tests, you naughty thing.
You can use it for non-model stuff, as well, but it’s a little bit trickier:
- loading and troubleshooting session objects (see Konstantin Gredeskoul’s blog)
- irb Mix tape from Chris @ err the blog again. A ton of tips for using
irb
and console, specifically. - Firing controller actions from the console from Canada Duane on BigBold snippets
If you have tips for how to use the console, please gimme comments!
Stupid console tricks
Here’s a handful of things you might not know about the console, or things you can do to make your console experience better. (The “making it better” stuff typically is done through supplementing Ruby’s irb
interactive Rubyconsole, which the Rails console is based on. You can place arbirtrary Ruby code into irb
‘s initialization script to affect the way it’s used.)
Autocomplete
The console has baked-in autocompletion functionality.
Start typing a class name, and hit tabit will either autocomplete it, or offer you a list of choices:
>> Str
String StringInput StringScanner
StringIO StringOutput Struct
It works for Ruby standard lib classes and Rails built-in classes (e.g., Dispatcher, ActionController, and so on), but not for the controllers and models in your app/
directory.
You can also use autocomplete for method names, on any class or object, regardless of where it’s fromso long as it’s within the console’s purview:
>> User.a
User.abstract_class User.after_update
User.abstract_class= User.after_validation
User.abstract_class? User.after_validation_on_create
User.accessible_attributes User.after_validation_on_update
(And so on. I cut the list short because it’s ridiculously long.)
If hitting tab after a class name and a period (e.g. User.[tab]
) doesn’t work the first time, hit it againthe console is trying to save you from making a grievous mistake which results in a list of hundreds of methods. The second time you hit tab, it will ask you:
>> User.
Display all 354 possibilities? (y or n)
Hitting n
will return you to the line you were typing, and y
will, of course, display them all. Use your space bar to page through the long lists, or Return
to go line by line.
Clearing the console
I don’t know about you, but I’m neurotic about using my terminal windowsI hate it when I’m constantly working at the bottom of the window, or there’s a huge swash of unnecessary output above where I’m working.
Unfortunately, the typical bash clear
command doesn’t work in the console:
>> clear
NameError: undefined local variable or method 'clear' for #
But ctrl + l
(that’s a lowercase L) will do the trick. For Mac users, Command + k
might be more comfy to type. (Thanks Phil!)
Turning on vi-style editing
You can turn on vi-style commands by editing your user account’s .inputrc
file:
$ cat ~/.inputrc
set editing-mode vi
This will also affect any other console-type tools which use the readline
library. Which is probably a happy side effect, but you’ve been warned!
Rollback all database changes on exit
err the blog has an article called irb Mix tape which describes, among other really useful things, how to run the console in a sandboxmeaning that all your database changes are completely reverted when you exit the console.
Basically, it looks like this:
$ script/console --sandbox
Loading development environment in sandbox.
Any modifications you make will be rolled back on exit.
>>
You can also use -s
as a flag instead of the more verbose --sandbox
. Sweet!
Keeping console history through quitting & reopening
When you exit the console, your history (accessed by those keyboard arrows) is wiped clean. But it doesn’t have to be that way. The irb Tips and Tricks page at RubyGarden shows you how you can make that history stick around.
Better helper support & more
See the Further Resources list for a bunch of links showing how to modify the console / irb
to make ’em better.
Like this article? Digg it… and consider dropping a few coins in the tip jar.
Further resources
Here are all the links I mentioned earlier in the article, and then some:
- Ruby on Rails: How to load session objects into console from Konstantin Gredeskoul
- Wirble (colorization,
ri
commands, etc., without editing the~/.irbrc
file) - Tracing method execution (for use with irb) from Ben Bleything
- Real console helpers from Chris @ err the blog (extends the console’s helper implementation to, well, actually work right)
- irb Mix tape from Chris @ err the blog again. A ton of tips for using irband console, specifically.
- irb Tips and Tricks from Ruby Garden (many of these have been implemented in the Rails console already, but not all!)
People:
- Ezra Zygmuntowicz inspired me to learn more about the console
- Phil Hagelberg contributed tips to this article
- why the lucky stiff writes about
irb
wizardry now and then
Unrelated Sidebar! Unrelated Sidebar!
I’d like to give a big, huge, belated Thank You, You Rock!! to all of the kind, kind folks who wrote in to help me with my CSS issue. The diversity of solutionsand really, the number of emails I gotblew me away. As you probably noticed, the problem did get fixed. Thanks to: Michael, Jenna, Arik, John, Chris L, Chris P, and Jeff. If you sent me a suggestion and I missed you in this list, I do apologizebut you have my gratitude nevertheless.
Oh… nice! Thanks for this awesome article 🙂
Great article. I will say that jumping into the console helped me move out of scaffold reliance and start actually learning ruby and what was going on in the back end.
oh, and btw, FP!
I’ve been using the console for months for cleaning up buggy data (from my old Java code, of course), handling user errors (mis-configured client kiosks), and general find-it and fix-it without doing it all in a SQL window.
In fact, it was only after doing a great deal of fixing by hand that I got around to making a controller to handle the same work (seeing as it wasn’t going to go away).
Nice Post, but I’ve got a couple general blog wishes. 1. Date stamp all posts right under the title, so that when people find it via google (or browse your past posts), they can easily see if it was published yesterday, last month, or two decades ago (this means include the year!) 2. Moderate comments and get rid of blatent spam. See your very own "A Not-So-Objective View of Ruby" post for several dozen samples.
Hey Jon, thanks for the feedback. I’m working (ever so slowly, I’m afraid) on the design issue you mentioned (among others). The date stamp is just a tiny part of how I’m going to make the site easier to browse. I’m just so goshdarn busy and I like writing so much more than writing HTML 🙂 <br/><br /> As for the second one, comments are now moderated. But I haven’t swept through and deleted all the old baddies yet. I need a trained monkey, I swear. <br/><br/> John: Yes, that’s why I decided to try and share the console goodness with everyone… it’s one more step on the road to building a "What to do to get real and become a real Rails developer" guide for those struggling with scaffolding addiction.<br/><br/> Ron, you have my sympathies!
YAML certainly looks much nicer.
I’m not sure I would do this permanently, but you can enter this in IRB to have all output in YAML instead of the Ruby-native inspect:
class Object; def inspect; y self; end; end
Hey Amy,
Very handy article, I was already sold on the idea of using the console and do so frequently yet I picked up a couple of very useful tips. Namely the "reload" and "sandbox" commands, extremely helpful especially as I’ve always been closing the console and restarting after making major changes!
I find that the console in production mode can be useful for administration type work (and checking out your Rails app stats).
Great great great!
Well done Amy.
Another amazing post! I already knew about the console and most of the stuff you posted, but I think reload! just made you my hero 😉
Bravo!
very useful–thank you!
i dont understand, what piece is useful in this article?
Auto complete actually does appear to work with classes in /app if you’ve already used them once. For example, if I do:
Person.find_all
Then next time around I can type:
Per
And hit TAB and voila, autocomplete. Console could be modified to load all of the classes in app on startup…that would be a nice side project if anyone is interested.
Great article! Thanks for the great info, Amy.
This is exactly what I’ve been looking for. It’s awesome that you’ve posted other resources too… very helpful. Thanks!
Awesome post. I’ve been using console for a while but your yaml tip and the magic _ variable were so useful that it’s like my love of the console is starting all over. Sweet, sweet Ruby/Rails second honeymoon! Thanks!
Great tips and tricks. Thanks for sharing!
Thanks for this! You have a minor typo in the Specifying Console Environment section.
$ script/console testing
should be:
$ script/console test
Hey, thanks John. Fixed.
[…] great thing about Rails is the console. You start you application in a terminal and you can use it (except for controllers and […]
[…] Secrets of the Rails Console Ninjas […]
[…] on, when I was getting into Ruby On Rails, Amy’s Secrets of the Rails Console Ninjas was an eye-opener… and then there was her other article that assured me that it was okay to […]
[…] If you really don’t understand how useful this is, then you really need to read the Secrets of the Rails Console Ninjas. […]
[…] yesterday, and I noticed a few rails console tricks I haven’t seen before. There’s been plenty of posts about irb and Rails before, but I’m hoping you’ll learn something new here. The […]
[…] функций rails консоли, которых не видел ранее. До этого было множество публикаций об irb и Rails, но я надеюсь, что из […]
[…] Secrets of the Rails Console Ninjas […]
[…] Secrets of the Rails Console Ninjas […]
http://www.good-food.Com.cn/
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
sdkdtec.com
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
stair child gate
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
48 inch wide baby gate
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
demo4195.cd.cdcidi.net
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
хиалуронова киселина
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
buy cci 41 primers
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
ice caps weed
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
game slot terbaik
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
Metal injection molding vs die casting
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
expomaster
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
38 super
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
amo hr model
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
cookies carts
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
space club disposable
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
Latest Series film
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
bulk small rifle primers small rifel primers
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
Buy A Phd Thesis
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
Buy a thesis
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
LIVE STREAM US OPEN GOLF 2022 LIVE FREE
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
sticky bun strain
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas
kompetisi cosplay di indonesia
slash7 with Amy Hoy » Blog Archive » Secrets of the Rails Console Ninjas