2

I need to grab the name of the lexically enclosing method in Ruby 1.8; e.g.

def foo
  this_method = __callee__  # => 'foo'
end

The above code is valid in Ruby 1.9, but fails in 1.8, since __callee__ was introduced in 1.9.

Any suggestions for doing this in 1.8? Kernel#caller looked promising, but seems to give me the call stack starting with the caller of the method, not the method itself.

I guess I could throw an exception, catch it, and grab the first element in the Exception#backtrace array, but my gut tells me that will be slow.

Josh Glover
  • 25,142
  • 27
  • 92
  • 129

2 Answers2

5

On Ruby 1.8.7 there is the __method__, not sure about 1.8.6.

Anyway, You can monkey patch the Kernel module:

module Kernel
  # Defined in ruby 1.9
  unless defined?(__callee__)
    def __callee__
      caller[0] =~ /`([^']*)'/ and $1
    end
  end
end
khelll
  • 23,590
  • 15
  • 91
  • 109
2

Have you checked whether the "backports" gem has it?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • The "backports" gem, has `__callee__`. I found it in the source for backports 1.18.2, complete with a test. – Wayne Conrad Feb 22 '11 at 22:37
  • Is `__callee__` any different from `__method__`? – Josh Glover Feb 23 '11 at 12:35
  • @Josh Glover, Not if you can believe its definition in backports: ` alias_method :__callee__, :__method__ unless (__callee__ || true rescue false)`. Formatting has taken away some double-underscores, but you get the idea. – Wayne Conrad Feb 25 '11 at 04:10