Execute Ruby or Python Scripts from Vim

2014-02-19 | vim

While developing Ruby script using Vim I frequently want to execute the script. This is easy to do by calling :!ruby % in Vim, but that’s rather a lot of typing. With a Vim mapping I shortened this:

Now I just have to hit \rx in Vim to execute the current buffer. (NB: I’m using the default Vim leader \.) Of course, sometimes I want to pass arguments to the script on the command line. This was easy to accomplish by omitting the carriage return at the end of the mapping:

Now I can hit \re, and before the script executes, I can enter the desired arguments and hit enter to execute the contents of the buffer.

Recently I started working with Python, and I wanted the same ability. My first iteration defined new mappings for Python:

This gave me \pe and \px mappings similar to the originals, but this placed an awkward load on my right pinky finger using a QWERTY keyboard layout. What I really wanted was the continue using the \rx shortcut I’d been using for years. This called for a function.

This version introduces a slight change to my workflow. Now when I hit \rx Vim prompts me for any additional arguments I want to pass to the script on execution — this is what \re and \pe did before. The original behavior of \rx and \px is gone. This means an extra carriage return when I’m executing the script without arguments, but it’s easier to type.


2013-05-17 | ruby

Ruby 1.9 introduced a nice addition to the Base64 module: Base64.strict_encode64. Whereas Base64.encode64 prettifies its output with newlines, Base64.strict_encode64 yields output without any superfluous line feeds.

This is a nice feature if you find yourself in need of RFC 4648-compliant output. You need this, for example, if you are generating policy documents for a form which uploads directly to Amazon S3. In such a scenario, instead of sending #gsub to the output of encode64 to strip out line feeds you can simply call strict_encode64.

Running RSpec Within Vim

2013-02-12 | rspec, vim

Below are a handful of mappings and a function I use to run various incantations of RSpec from within Vim.

When a spec file is open in the current buffer I can do the following:

\rlRun the example the includes the current line, e.g., rspec spec/.../foo_spec.rb -l N. (If the current line is an it block, only that example is run. If the current line is a describe block, all examples within the context are run — I’m particularly fond of this feature of RSpec.)
\rfRun the entire spec file, e.g., rspec spec/.../foo_spec.rb.
\rdRun all the spec files in the current spec file’s directory, e.g., rspec spec/....
\rsRun the entire spec suite, e.g., rspec spec.

The way the mappings are configured the first three mappings run rspec with the documentation format. The last one runs rspec with the progress (dots) format. I find the former nice when I’m running a small number of examples and the latter perferable when I’m running a large number of examples.