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-11-23
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.
super
In the general case (not necessarily Rails), this is the way to go about things
def initialize
super
customer_suff
end
Alternatively write custom constructors that do the extra work while delegating to the original initialize
def self.build
record = new
record.foo = true
record
end
Lastly available, use callbacks like after_initialize