Skip to content

Instantly share code, notes, and snippets.

@fakefarm
Last active May 31, 2016 18:51
Show Gist options
  • Save fakefarm/156866e6683c97dca3999ec2d2ddb64f to your computer and use it in GitHub Desktop.
Save fakefarm/156866e6683c97dca3999ec2d2ddb64f to your computer and use it in GitHub Desktop.
I know where I am but not how I got here

I know where I am but not how I got here

By @tenderlove. Full post I am puts debugger

Sometimes I’ll be debugging an issue and know where the problem is, but not how I got there. For those times I’ll just do puts caller to get the callstack.

For example I have this code:

LOOKUP = Hash.new { |h, k| h[k] = Type.new(k) unless k.blank? }

But I need to know how the default block is getting called, I do this:

  LOOKUP = Hash.new { |h, k|
    puts "#" * 90
    puts caller
    puts "#" * 90
    h[k] = Type.new(k) unless k.blank?
  }

The above code will print out 90 hash tags, then the call stack, then 90 more hash tags. I print out the hash tags so that if it gets called multiple times, I can easily differentiate the call stacks. If I only want to print the call stack once, just use exit! after printing the callstack, or call raise. raise will show an exception so you see the stack anyway.

I only want to see the stack in certain cases

This is debugging code, so you can do whatever you want. Lets say I just want to see the stack when adding something to the hash. Just do this:

  LOOKUP           = Hash.new { |h, k|
    unless k.blank?
      puts "#" * 90
      puts caller
      puts "#" * 90
      h[k] = Type.new(k)
    end
  }

Since I’m going to throw this code away anyway, I’m free to add any kind of weird conditionals I’d like!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment