ruby picture

RCR 350: Make Kernel#caller return Array of Structs

Submitted by fryedpeach (Tue Oct 17 11:25:15 UTC 2006)

Abstract

Make Kernel#caller return Array of Structs that have 3 members, file, line, and method.

Currently, Kernel#caller returns Array of Strings.

Problem

When you want to know where your method was called, you can use Kernel#caller. However, it returns an Array of mere Strings.

That means, when you want just a name of the method, you need parsing:

 def parse_caller(caller_output)
   if /^(.+?):(\d+)(?::in `(.*)')?/ =~ caller_output
     {:file => $1, :line => $2.to_i, :method => $3}
   end
 end
 parse_caller(caller.first)[:method]

That's sometimes a pain.

Proposal

If Kernel#caller returned Array of Structs like this:

 class CallerInfo < Struct.new(:file, :line, :method)
   def to_s
     "#{file}:#{line}:in `#{method}'"
   end
 end

The code above could be simpler:

 caller.first.method

Analysis

This change may break backward compatibility. CallerInfo#to_str may be needed.

Implementation

 module Kernel
   CallerInfo = Struct.new(:file, :line, :method)
   class CallerInfo
     def to_s
       "#{file}:#{line}:in `#{method}'"
     end
   end
   alias unstructured_caller caller
   def caller(level=1)
     if level < 0
       raise ArgumentError, "negative level (#{level})"
     end
     unstructured_caller(level+1).collect do |item|
       /^(.+?):(\d+)(?::in `(.*)')?/.match(item)
       CallerInfo.new($1, $2.to_i, $3)
     end
   end
   module_function :caller
 end

CallerInfo#to_s is imcomplete.

ruby picture
Comments Current voting
This idea has been around a long time in one form or another. I assume Matz hasn't embraced it simply becuase it could break lots of code. In that light I think it woudl better to use a new method, e.g. #call_stack. (And actually that might be in the works for 1.9+ though I can't recall for certain off hand). As such I think it will return either an array of arrays or, better, an array of a special object, like a Frame or Tracepoint (from Sydney and Facets, respectively).

In whatever form it takes I strongely favor it too.

T.


Adding new method (like Kernel#structured_caller ?) may be more acceptable than my proposal. I like either.

fryedpeach


Strongly opposed 0
Opposed 0
Neutral 0
In favor 1
Strongly advocate 2
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .