I read Sandi Metz POODR and came across a coding principle that I don't quite understand. Here is the code:
class Bicycle attr_reader :size, :chain, :tire_size def initialize(args = {}) @size = args[:size] || 1 @chain = args[:chain] || 2 @tire_size = args[:tire_size] || 3 post_initialize(args) end end class MountainBike < Bicycle attr_reader :front_shock, :rear_shock def post_initialize(args) @front_shock = args[:front_shock] @rear_shock = args[:rear_shock] end end mb = MountainBike.new(front_shock: 4, rear_shock: 5) puts mb.size puts mb.chain puts mb.tire_size puts mb.front_shock puts mb.rear_shock
This code outputs 1,2,3,4,5 for the corresponding attributes. What I do not understand is the search method.
When a mountain bike is created because it does not have its initialize method, it will move the method search chain to its superclass ( Bicycle ). But now it seems from there that the Bike then goes back to the post_initialize MountainBike method. Instead of continuing the chain of methods, how can it come back? Is post_initialize a ruby โโkeyword, such as initialize , in which it performs some special function? Are there any other ruby โโintrospection methods that I can use to see what happens?
source share