Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I make private class constants in Ruby

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 
like image 490
DMisener Avatar asked May 20 '10 13:05

DMisener


People also ask

Can constants be private?

Answer 5518b447937676d350004c42. Constants can be used with public or private just fine!

How do you create a constant in Ruby?

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.

How do you make a class private in Ruby?

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.

Can a class method be private Ruby?

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.


2 Answers

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 
like image 139
Renato Zannon Avatar answered Oct 20 '22 11:10

Renato Zannon


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.

like image 39
harald Avatar answered Oct 20 '22 10:10

harald