override a private static property on a subclass in ruby

In Ruby, you can override a private static property on a subclass by defining a class method with the same name as the property on the parent class and using @@ notation to access the private static property. Here's an example:

main.rb
class Parent
  private_class_method def self.my_private_static_property
    'hello, world!'
  end
end

class Child < Parent
  def self.my_private_static_property
    @@my_private_static_property = 'goodbye, world!'
    super
  end
end

puts Parent.send(:my_private_static_property) # Outputs "hello, world!"
puts Child.send(:my_private_static_property) # Outputs "goodbye, world!"
381 chars
16 lines

In this example, the Parent class has a private class method called my_private_static_property which returns the string "hello, world!". The Child class defines the same class method, but first sets a new value for the private static property @@my_private_static_property and then calls super to invoke the parent implementation of the method, which returns the new value of the private static property.

Calling Parent.send(:my_private_static_property) outputs "hello, world!" because the method is defined on the Parent class and is private, so it can only be accessed via reflection (send). Calling Child.send(:my_private_static_property) outputs "goodbye, world!" because the Child class overrides the method to change the value of the private static property before invoking the parent implementation of the method.

gistlibby LogSnag