---
title: irb & script/console tips
teaser:
tags: web,ruby,rails
author: Dan Croak
published_on: 2008-12-23
---

Let's get interactive. You can learn a lot about your application from irb and
by extension, `script/console`.

### Wirble: colors

Color matters. You're picky about your [text editor syntax
highlighting](http://alternateidea.com/blog/articles/2006/1/3/textmate-vibrant-ink-theme-and-prototype-bundle)
and maybe you use the excellent
[redgreen](https://rubyforge.org/projects/redgreen/) gem for colors in your test
backtraces. Gotta have it in irb, too.

First, install Wirble:

<kbd>sudo gem install wirble</kbd>

Then, in your `~/.irbrc`:

```ruby
require 'rubygems'
require 'wirble'
Wirble.init
Wirble.colorize
```

### Wirble: history

Wirble has an added bonus: history.

```irb
irb(main):001:0> history = "History?"
=> "History?"
irb(main):002:0> exit
```

Without Wirble, if you drop back into irb, you can't arrow up to your previous
commands. With Wirble, you can.

### Wirble: auto-completion

As if that's not enough, Wirble gives you auto-completion, too. In irb:

```irb
>> un_momento = "Spanish for like, 'hold the phone!'"
=> "Spanish for like, 'hold the phone!'"
```

Type, un, then tab:

    >> un
    un_momento   undef        unless       untaint      untrace_var  until

### Local methods

Stick this in your `~/.irbrc`:

```ruby
# Easily print methods local to an object's class
class Object
  def local_methods
    (methods - Object.instance_methods).sort
  end
end
```

Use the `local_methods` method like this:

```irb
>> class BasketballPlayer
>>   attr_accessor :name
>>
?>   def champion?
>>     name == "Kevin Garnett"
>>   end
>> end
=> nil
>> kevin_garnett = BasketballPlayer.new
=> #<BasketballPlayer:0x11988f8>
>> kevin_garnett.name = "Kevin Garnett"
=> "Kevin Garnett"
>> kevin_garnett.champion?
=> true
>> kevin_garnett.local_methods
=> ["champion?", "name", "name="]
```

<object width="425" height="344">
  <param name="movie"
    value="http://www.youtube.com/v/6dk7Il3EqI0&amp;hl=en&amp;fs=1" />
  <embed src="http://www.youtube.com/v/6dk7Il3EqI0&amp;hl=en&amp;fs=1"
    type="application/x-shockwave-flash" width="425" height="344" />
</object>

### Aliases

Don't forget you can alias in irb. The only one I have is:

    alias q exit

It makes irb feel more
[Vim-ish](https://thoughtbot.com/blog/thoughtbot-is-filled-with-vim-and-vigor).

### Create test fixtures for a third party service

Your app uses the Flickr API. You want your test suite to use legitimate data
but not hit the service.

Given the actual call to the service is:

```ruby
FlickrClient.search("Bruce Springsteen")
```

Run the query in script/console and convert the data into yaml:

```ruby
yaml = FlickrClient.search("Bruce Springsteen").to_yaml
```

Then use your old Ruby friend, File.open with the write option (w) to dump it to
a file:

```ruby
File.open("test/fixtures/flickr/springsteen.yml", "w") { |file| file << yaml }
```

Add this to your `test_helper.rb`:

```ruby
def load_yaml_fixture(path)
  absolute_path = File.join(RAILS_ROOT, "test", "fixtures", path)
  YAML::load_file absolute_path
end
```

Voila, when you need to mock out calls to the third party service, you can now
use this in your test code:

```ruby
load_yaml_fixture("springsteen.yml")
```

This pattern is repeatable for any third party service. Just replace the actual
call with whatever you're working on, and name the fixture something
intention-revealing.

<object width="425" height="344">
  <param name="movie"
    value="http://www.youtube.com/v/gC7hanPld7A&amp;hl=en&amp;fs=1" />
  <embed src="http://www.youtube.com/v/gC7hanPld7A&amp;hl=en&amp;fs=1"
    type="application/x-shockwave-flash" width="425" height="344" />
</object>

### Print SQL to standard out

Oftentimes `script/console` is used for debugging, and what better way to do
that than to get the <abbr title="Structured Query Language">SQL</abbr>
generated by each method call. Stick this in your `~/.irbrc`:

```ruby
# Log to STDOUT if in Rails
if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
  require 'logger'
  RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
end
```

This gets you:

```irb
>> videos = Video.limited(3)
  Video Load (0.4ms)   SELECT * FROM `videos` LIMIT 3
=> [#<Video id: 1, ...>]
```

Without the `~/.irbrc` love, you'd be missing:

<pre>
<samp>Video Load (0.4ms)   SELECT * FROM `videos` LIMIT 3</samp>
</pre>

### pp

After you've required rubygems for Wirble, require pretty print, too:

```ruby
require 'pp'
```

This is just a nice way to have better formatting at your fingertips. It's
especially helpful when dealing with an Array of ActiveRecord objects:

```irb
>> pp videos
[#<Video id: 1, youtube_id: "TcMklv40YMY", name: "Merb, Rubinius and the
Engine Yard Stack", upload_time: nil, view_count: 6171, description: "Google
Tech Talks\nOctober 20, 2008\n\nABSTRACT\n\nIn th...", created_at: "2008-12-21
00:32:33", updated_at: "2008-12-21 00:32:33">, #<Video id: 2, youtube_id:
"JySmT-dGOj0", name: "MERB SPORTS Team-Vorstellung 2008", upload_time: nil,
view_count: 495, description: "MERB SPORTS stellt sich für die VDRM-Saison 2008
v...", created_at: "2008-12-21 00:32:33", updated_at: "2008-12-21 00:32:33">,
#<Video id: 3, youtube_id: "6bc-FNNWIsM", name: "Merb && Moi", upload_time:
nil, view_count: 58, description: "Amusing yes?", created_at: "2008-12-21
00:32:33", updated_at: "2008-12-21 00:32:33">]
```
