Eugen
Eugen

Reputation: 155

Look what is calling the initialize method of a class

So I have a too much code to post, and I have googled but dont found any solution.

I have a class e.g:

class Example
  def initialize
    #some_code
    p "class was initialized"
  end
end

The console prints "class was initialized" two times, and I can only find one line where the class gets initialized. My question is, if there are some methods to look from where the initialize method of the class is called, so I can find out why its initialized two times.

Upvotes: 0

Views: 53

Answers (2)

sawa
sawa

Reputation: 168101

class Example
  def initialize
    #some_code
    p "class was initialized"
    puts caller_locations
  end
end

In legacy Ruby:

class Example
  def initialize
    #some_code
    p "class was initialized"
    puts caller
  end
end

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

You can raise/catch an exception, which will get you access to stacktrace.

class Example
  def initialize

    begin
      raise
    rescue => e
      puts e.backtrace
    end
  end
end

Upvotes: 1

Related Questions