Be careful calling constructors on subclasses without super

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the object-oriented-programming category.

Last Updated: 2024-03-02

I was working in a Ruby codebase where the constructor is called initialize. I was defining a class that inherited from ActiveModel::Base and used initialize in this sub-class: It caused weird effects.

Due to how heavily ActiveModel::Base uses the initialize method internally, defining an initialize method on a subclass (e.g. TutorSearch < ActiveModel::Base) — one that DOES NOT include super - will not behave correctly.


In the general case (not necessarily Rails), this is the way to go about things

  def initialize