Automatic Color Coding for script/console and irb

written by jared on June 26th, 2010 @ 09:18 PM

A friend recently turned me onto Awesome Print, a pp replacement:

Michael Dvorkin's awesome_print on GitHub

What Awesome Print does is automatically color code your script/console and irb output when you use it as a pp replacement. What gets even more trick though, nay awesome, is triggering it automatically so all output is color coded. Here's the magic.

Edit your .irbrc file in ~ and add the following lines:

begin
  require "ap"
  IRB::Irb.class_eval do
    def output_value
      ap @context.last_value
    end
  end
rescue LoadError => e
  puts "ap gem not found.  Try typing 'gem install awesome_print' to get super-fancy output."
end

You may also need to add this line at the top of the file:

require 'rubygems'

if your .irbrc file does not already contain it. Mine did, which is why I omitted it above.

Now the results of anything in script/console will have Awesome Print used automatically:

awesome_print output

Comments

  • Stéphan K. on 26 Jun 22:58

    Oh wow, that adds some serious style to my IRB console! Thanks for that, and do pat your friend on the shoulder.

  • Jay Sanders on 27 Jun 00:16

    Fantastic post! When I used to work with php, I wrote my own diagnostics class which would work like pretty print, but would be much more readable and easier to review. I missed this method very much when I switched to Ruby many years ago, and have never been satisfied with pretty print. It does make it easier to read, but is still a bit of a mess.

    awesome_print is just what the doctor ordered, and your instructions on making it the default rendering tool within irb are extra spicy! Now I will always have awesome output and never know the difference!

    One important note. When I first tried to use your script, it triggered the LoadError saying: “ap gem not found. Try typing ‘gem install awesome_print’ to get super-fancy output.” just like you designed it. I referenced the awesome_print GitHub page and found that they included RubyGems before including ap in their script. I combined the two and the results are perfect!

    Right after begin and before the require “ap”, insert the RubyGems require:

    require “rubygems” require “ap”

    Thanks again for making me aware of this awesome gem!!

  • Jones Lee on 01 Jul 11:45

    I follow but failed to make it work under RVM. Any idea?