PYe
PYe

Reputation: 35

Ruby how do i get current class name after super

For debugging purpose, i want to output current class name when i initialize a new object. So, this is what i have done.

class Base
  def initialize
      puts "line 2: " + self.class.to_s
  end
end

class Custom < Base
  def initialize
      puts "line 1: " + self.class.to_s
      super
  end
end

The problem is in the console, the output is

line 1: Custom
line 2: Custom

I understand self is an object of Custom. My question is how to get Base#initialize to print Base? So that my final output will be

line 1: Custom
line 2: Base

And when i initialize a Base object, it will print line 2: Base as well.

Upvotes: 1

Views: 702

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Have I missed something?

class Base
  def initialize
    puts "line 2: Base"
  end
end

class Custom < Base
  def initialize
    puts "line 1: Custom"
    super
  end
end

Custom.new
  # line 1: Custom
  # line 2: Base
Base.new
  # line 2: Base

Upvotes: 1

Eric Duminil
Eric Duminil

Reputation: 54223

Since a class is also a module, you can use Module.nesting.

Also, to make sure you don't get TypeError: no implicit conversion of Class into String, you should use string interpolation :

class Base
  def initialize
    puts "line 2: #{Module.nesting.first}"
  end
end

class Custom < Base
  def initialize
    puts "line 1: #{Module.nesting.first}"
    super
  end
end

Custom.new
# line 1: Custom
# line 2: Base
Base.new
# line 2: Base

Upvotes: 3

Related Questions