add a protected static property to a class in ruby

In Ruby, we can define a static property (i.e. class-level variable) with the @@ notation. To make it protected, we can use the protected_class_method or protected_singleton_method method.

Here's an example of how to define a protected static property in a class:

main.rb
class MyClass
  @@my_protected_static_property = 42

  protected_class_method :my_protected_static_property=

  def self.set_my_protected_static_property(value)
    @@my_protected_static_property = value
  end

  def self.get_my_protected_static_property
    @@my_protected_static_property
  end

  protected

  def self.my_protected_static_property=(value)
    @@my_protected_static_property = value
  end
end
411 chars
20 lines

In this example, we define a static variable @@my_protected_static_property and a setter method my_protected_static_property= as protected. We also define a getter method get_my_protected_static_property and a public setter method set_my_protected_static_property that can be called from outside the class.

To access the protected static property, we can use the send method with the name of the protected method:

main.rb
MyClass.send(:my_protected_static_property=, 123)
50 chars
2 lines

This code will set the value of the protected static property to 123. Note that we have to use send to call the protected method from outside the class.

gistlibby LogSnag