Sometimes I want to have a constant in my modules or classes that I don't want to be part of my API – I want a private constant.
The Module class contains the method private_constant which we can use to do just that. And since Module is the ancestor class of Class, it's available for classes too.
Let assume I have a module that looks like this:
module MyModule
MY_CONSTANT = 'billy_ruffian'.freeze
private_constant :MY_CONSTANT
def self.my_constant
MY_CONSTANT
end
end
The constant, MY_CONSTANT, is hidden by the private_constant statement. I try and access it from outside the module, I get:
MyModule::MY_CONSTANT
private constant MyModule::MY_CONSTANT referenced (NameError)
But the constant remains accessible within the module:
MyModule.my_constant
=> "billy_ruffian"