In Ruby how does one create a private class constant? (i.e one that is visible inside the class but not outside)
class Person SECRET='xxx' # How to make class private?? def show_secret puts "Secret: #{SECRET}" end end Person.new.show_secret puts Person::SECRET # I'd like this to fail
Answer 5518b447937676d350004c42. Constants can be used with public or private just fine!
Ruby ConstantsConstants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.
The classic way to make class methods private is to open the eigenclass and use the private keyword on the instance methods of the eigenclass — which is what you commonly refer to as class methods.
there's no such thing as "a private section" in Ruby. To define private instance methods, you call private on the instance's class to set the default visibility for subsequently defined methods to private... and hence it makes perfect sense to define private class methods by calling private on the class's class, ie.
Starting on ruby 1.9.3, you have the Module#private_constant
method, which seems to be exactly what you wanted:
class Person SECRET='xxx'.freeze private_constant :SECRET def show_secret puts "Secret: #{SECRET}" end end Person.new.show_secret # => "Secret: xxx" puts Person::SECRET # NameError: private constant Person::SECRET referenced
You can also change your constant into a class method:
def self.secret 'xxx' end private_class_method :secret
This makes it accessible within all instances of the class, but not outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With