Skip to content

Instantly share code, notes, and snippets.

@capnslipp
Created October 18, 2012 22:42
Show Gist options
  • Select an option

  • Save capnslipp/3915203 to your computer and use it in GitHub Desktop.

Select an option

Save capnslipp/3915203 to your computer and use it in GitHub Desktop.
where_am_i: tiny Ruby debugging extension to sum up the current location in the object graph
## encoding: utf-8
## author: Slipp Douglas Thompson <http://slippyd.com/>
class Object
  # notice: it's a verbal statement
  def where_i_am
    object_index = self.object_id
    class_name = self.class.name
    
    class_lineage = begin
      h = {}
      all_ancestors = self.class.ancestors[1..-1]
      inspecting_class = self.class
      
      loop do
        break unless inspecting_class
        
        h[inspecting_class] = nil
        loop do
          anni = all_ancestors[0]
          
          break if anni == inspecting_class.superclass
          
          h[inspecting_class] ||= []
          h[inspecting_class] << anni
          
          all_ancestors.shift
        end
        
        inspecting_class = inspecting_class.superclass
        all_ancestors.shift
      end
      
      h
    end
    class_lineage_s = h.inject([]) {|a, lineage|
      a << "#{lineage[0].inspect}" + (lineage[1] ? " ∋ {#{lineage[1].collect(&:inspect).join(', ')}}" : '')
    }.join(' < ')
    
    self_description = self.to_s
    
    return "inside of object ##{object_index}\n" +
      "\tinstance of class: #{class_lineage_s}\n" +
      "\tself-described as: #{self_description}"
  end
  
  # notice: it's a verbal question
  def where_am_i
    puts where_i_am
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment