Red Green Repeat Adventures of a Spec Driven Junkie

TIL: Better Rails Debugging with $stderr

On this week’s Ruby Weekly, I read Alex Taylor’s Focused ‘puts’ Debugging with STDERR article. This tip is great as it requires only two steps to implement:

  1. Use $stderr.puts instead of puts
  2. Start the Ruby on Rails server with: rails server 1>/dev/null

This tip is a game changer when a Ruby on Rails project has LOTS of output to the console. Finding any puts messages require intense searching through the terminal/tmux.

One thing I did miss is being able to view large hashes in a structured format. Pretty print does a really good job, but now hashes look like:

"Ruby hash printed without pretty print"

So, to have the Pretty Print gem print to stderr requires:

PP.pp(<hash>, $stderr)

Which seems obvious now, but for some reason in Ruby 2.5 (that includes Pretty Print by default) pp(<hash>, $stderr) did not work.

Now, when I debug using $stderr, I print hashes with: PP.pp(<hash>, $stderr) and the result is:

"Ruby hash printed with pretty print"

So, use $stderr.puts and PP.pp(<item>, $stderr) when running $ rails s 1>/dev/null.