Mikey T.K.
Mikey T.K.

Reputation: 1160

Getting the name of the calling class in Ruby

I'm trying to figure out how to get the name of the class that called a module function in a plugin-based application of mine.

caller seems to give me a file/line number, which is workable, but seems a bit hacky and not idiomatic.

Example code:

module AwesomeModule
  def self.get_caller
    puts #some unknown code here
  end
end


class AwesomeClass
  def initialize
    AwesomeModule::get_caller
  end
end

a = AwesomeClass.new # ideal return => "AwesomeClass"

Upvotes: 4

Views: 1748

Answers (1)

spike
spike

Reputation: 10004

You typically use ruby modules by including them. Try this:

module AwesomeModule
  def get_caller
    self.class
  end
end

class AwesomeClass
  include AwesomeModule
  def initialize
    get_caller
  end
end

a = AwesomeClass.new #  "AwesomeClass"

Also, note that in your question get_caller is being called on the AwesomeModule module itself, further complicating the issue.

Upvotes: 4

Related Questions