Method Name Hack

Posted by Carsten Nielsen
on Friday, June 13

Ruby lets you do some pretty fun stuff, from highly elegant and useful to interesting and hacky. This is more of a hack than anything but it demonstrates some cool concepts.


module ::Kernel

  private
  # Allows you to get the name of the current method inside that method.
  # Example:
  #
  #   def hello
  #     __method_name__
  #   end
  #
  #   hello # => "hello"
  def __method_name__
    caller[0].scan(/`(.*)'/).to_s
  end

end

Ruby let’s you extend anything and everything, which is pretty powerful. The two preceding colons in ::Kernel tell Ruby to access the Kernel module in the global object space, if we were already there they would not be necessary but to be safe it’s best to add them.

Ruby maintains a call stack which is basically an array of strings that look like:


/Users/carsten/Projects/coolness/cool.rb:12:in `awesome_method'

This lets us know the path and file name as well as the line number and method name; neat. Then we just do a cute little regular expression scan and we can see the name of the method we are inside of.

Comments

Leave a response

  1. Andrew BrownJune 19, 2008 @ 02:16 PM

    Thats 3L1T3.

    Do you think I could do the same in mxml?

    <kernal> <methodname_ onEnterEvent=”caller_scan(‘(.*)’)” /> </kernal>