1

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?

jdno
  • 4,104
  • 1
  • 22
  • 27

1 Answers1

2

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
Jacob Brown
  • 7,221
  • 4
  • 30
  • 50
  • is the `singleton_class.send` really needed here? – Mohammad Mar 09 '16 at 17:00
  • 1
    It's just an alternative to opening the `singleton_class` as in the question example. I would prefer it e.g. in this case, when I'm only doing one call in that context, but I think it's a matter of personal preference. The `send` is required because `attr_writer` is a private method. – Jacob Brown Mar 09 '16 at 17:33
  • Thanks @kardeiz! That works and was way too easy. Feels like my Ruby is getting a little rusty. – jdno Mar 11 '16 at 08:56