8

I am using Ruby on Rails 3.2.2 and, in order to display warning messages for development purposes, I am using logger.warn in my code. I would like to retrieve the method name in which that logger.warn runs so to output that method name to the log file.

class ClassName < ActiveRecord::Base
  def method_name
    # Note: This code doesn't work. It is just a sample.
    logger.warn "I would like to retrieve and display the #{self.class.to_s}##{method_name}"
  end
end

In the log file I would like to see:

I would like to retrieve and display the ClassName#method_name

Is it possible? If so, how can I make that?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
user12882
  • 4,702
  • 9
  • 39
  • 54
  • 1
    possible duplicate of [Get the name of the currently executing method in Ruby](http://stackoverflow.com/questions/199527/get-the-name-of-the-currently-executing-method-in-ruby) – Andrew Marshall May 06 '12 at 02:38

1 Answers1

25
class ClassName < ActiveRecord::Base
  def method_name
    logger.warn("I would like to retrieve and display the #{self.class}##{__method__}")
  end
end

this should do the job.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Bhushan Lodha
  • 6,824
  • 7
  • 62
  • 100