Created
August 20, 2010 11:44
-
-
Save mikezter/540132 to your computer and use it in GitHub Desktop.
Get calling method name in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CallerMethodName | |
extend self | |
def caller_method_name | |
parse_caller(caller(2).first).last | |
end | |
def parse_caller(at) | |
if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at | |
file = Regexp.last_match[1] | |
line = Regexp.last_match[2].to_i | |
method = Regexp.last_match[3] | |
[file, line, method] | |
end | |
end | |
# guessing from file name | |
def caller_class_name | |
File.basename(parse_caller(caller(2).first).first, '.rb').classify | |
end | |
end | |
if __FILE__ == $PROGRAM_NAME | |
require 'test/unit' | |
require 'rubygems' | |
require 'active_support/inflector' | |
class TestCallerMethodName < Test::Unit::TestCase | |
class A | |
extend CallerMethodName | |
def self.gief_method | |
caller_method_name | |
end | |
def self.gief_class | |
caller_class_name | |
end | |
end | |
# should parse a stacktrace line | |
def test_parse_caller | |
stacktrace = "/opt/ruby-enterprise/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding'" | |
assert_equal ['/opt/ruby-enterprise/lib/ruby/1.8/irb/workspace.rb', 52, 'irb_binding'], CallerMethodName.parse_caller(stacktrace) | |
end | |
def test_caller_class_name | |
assert_equal 'CallerMethodName', A.gief_class | |
end | |
def test_caller_method_name | |
assert_equal 'test_caller_method_name', A.gief_method | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment