1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

Spotlight on Gems: Sketches

By

Sketches is a really cool gem that helps you test out code in IRB. Without a tool like Sketches to test out some code in IRB you can either type it directly into IRB, or save it in a file and load it with IRB. Both are cumbersome: typing into IRB is problematic and if you use a file, you have to reload every time you make a change. This is what Sketches solves, it will automatically reload a Ruby script (referred to as a "Sketch") every time you make changes to it. This allows you the comfort of editing in your favorite editor and having easy access to the code in IRB.

Installing Sketches

Sketches is a pure-Ruby gem with no major dependencies. It's installed as any other gem is installed.

$ sudo gem install sketches

Using Sketches

To jump right into sketches, open up an IRB prompt with both the Rubygems and Sketches libraries included.

$ irb -rubygems -rsketches

This will start up your IRB prompt, and it will look normal. Before you can open up a sketch, you will have to configure an editor to use. This command depends on your platform. On Linux, I use the editor "gvim," but you can use any other editor. Also, if you have your EDITOR environment variable set, you can skip this step, as it will pick up on this automatically.

irb(main):001:0> Sketches.config :editor => 'gvim'

Finally, you can start up a sketch. Run the method sketch and your editor will open.

irb(main):002:0> sketch

In this new editor window, you can input your Ruby code. Whenever you save this file to the disk, your changes will automatically be reflected in IRB. For example, input the following code into the editor windows and save the changes.

def method
  puts "test"
end

And then run this method in IRB, you will get the output of "test". Next, change the method to output a different string, save the file and run the method again. You will get the changed output without having to tell the IRB prompt the code has changed, just like magic!

The "Sketch" that was opened in your editor window is stored in a temporary file. There are two ways to make reusable, named sketches. The first way is to simply pass a name to the sketch method.

irb(main):005:0> sketch :mytest

Now, if you save something in this file, close the editor window, and open it up again, your changes will be remembered. You can also just give it the path to a Ruby file. This takes your sketches out of the temporary directory, and allows you to test files from your projects.

  1. About.com
  2. Technology
  3. Ruby
  4. Gems
  5. Spotlight on Gems: Sketches

©2014 About.com. All rights reserved.