ClassProp

ClassProp allows you to set properties of a class which can be inherited or overridden by subclasses. For example, in the following code, the Base class is created and includes ClassProp. Then it defines an inheritable property called fco. Finally, it sets the value of that property to base.

class Base
    include ClassProp
    define_class_prop 'fco'
    self.fco = 'base'
end

The fco property is now available from Base.

puts Base.fco # => 'base'

Another class can inherit from Base.

class X1 < Base
end

If X1 does not define its own fco property, then when that property is retrieved from X1 it returns Base.fco.

puts X1.fco # => 'base'

X1 can set its own value for fco.

class X1
    self.fco = 'x1'
end

That gives us this output.

puts X1.fco # => 'x1'

To delete a class property (so that the property is again inherited from the superclass) use delete_class_prop.

class X1
    delete_class_prop 'fco'
end

puts X1.fco # => 'base'

You can set a property so that it must be defined by subclasses. To do so, set the property to ClassProp::MustDefine. If an inheriting class does not define that property then an error is raised when the property is retrieved.

class Base
    include ClassProp
    define_class_prop 'fco'
    self.fco = ClassProp::MustDefine
end

class X1 < Base
end

X1.fco # raises exception 'must-define-class-class-property: fco'

Install

gem install classprop

Author

Mike O'Sullivan [email protected]

History

version date notes
1.0 Feb 24, 2020 Initial upload.
1.1 Feb 24, 2020 Reworked interface.