A Different REPL Workflow in Ruby

Ruby — squarism @ 8:42 pm

Normally what I do is open an editor and start coding. In Textmate, I’ll hit Cmd+R to just run it as a big procedural file for something simple. If it gets too complicated, I’ll put it in a class. If something is confusing, I’ll break out to irb. The problem with this workflow is that you have to copy and paste a lot of code back and forth to get to “the breakpoint”.

In rails, I’d just put a binding.pry and magically, I’m at the breakpoint to play around at that point in time. No copying and pasting. Nice.

After watching a bunch of destroyallsoftware screencasts though, I like his one setup from episode #7 where he inlines rspec tests. Combine this with watchr and I might have a new favorite.

Let’s say I had the following hello world example.

When I run it in Textmate with Cmd+R, it doesn’t do anything. Because there’s no “main”. So then I have to add:

Great! But wait a minute, when I use it in another class, it’s going to print “Hello Variable!” out. So then I take it out? Then to test it again, I put it back in? This workflow although easy kind of sucks.

So let’s just inline some rspec. But before we even do that, we need rspec and watchr. We are going to use watchr to watch our files for changes. It’s best to install rev (Linux) or ruby-fsevent (Mac) for filesystem event firing.

gem install watchr rspec ruby-fsevent

Next, run this in a terminal and put it so where you can see it run while in your editor:
watchr -e 'watch("hello.*\.rb") {|m| system("clear && rspec -c #{m};") }'

Like this:

When you save the file (even without changes), it should say:
No examples found.

Finished in 0.00007 seconds
0 examples, 0 failures

Ok, now let’s inline some rspec tests to test our class.

Now we will get this nice rspec to the right in color immediately upon saving:

So how about irb? What if we want to learn/play in the code? Well now that we have a class and a shell instead of Textmate, we can use pry again.

And now when we save, we’ll be popped into a Pry shell.

So give this a shot and see if you like this as an alt workflow.

2 Comments »

  1. [...] whatever. That’s regex stuff. Let’s try applying what we’ve learned from our last post and create an inline rspec test to do what we [...]

  2. [...] could also try my inline rspec trick even though that still uses libevent for triggering the test [...]

RSS feed for comments on this post. TrackBack URI

Leave a comment

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2013 SQUARISM | powered by WordPress with Barecity