Search code examples
rubyinheritanceclass-instance-variables

How to declare Class Instance Variable in inherited class automatically


I am using Class Inheritance Variables in Ruby to keep track of the number of instances I've created so far. To keep my code DRY, I implemented most of the logic in a base class that all my other classes inherit from.

class Entity
  @instance_counter = 0

  class << self
    attr_accessor :instance_counter
  end

  def initialize
    self.class.instance_counter += 1
  end
end

This works perfectly fine except for one thing:

I have to define @instance_counter in each child class, or I will get an NoMethodError.

class Child < Entity
  @instance_counter = 0
end

Is there a way to declare the variable in each child automatically so that I don't have to do it manually?


Solution

  • I don't know if this is the best way, but here is how I might do it:

    class Entity
      singleton_class.send(:attr_writer, :instance_counter)
      def self.instance_counter; @instance_counter ||= 0; end
      def initialize
        self.class.instance_counter += 1
      end
    end