How to I make private class constants in Ruby

RubyAccess SpecifierClass Constants

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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.

Solution 3 - Ruby

Instead of a constant you can use a @@class_variable, which is always private.

class Person
  @@secret='xxx' # How to make class private??

  def show_secret
    puts "Secret: #{@@secret}"
  end
end
Person.new.show_secret
puts Person::@@secret
# doesn't work
puts Person.class_variable_get(:@@secret)
# This does work, but there's always a way to circumvent privateness in ruby

Of course then ruby will do nothing to enforce the constantness of @@secret, but ruby does very little to enforce constantness to begin with, so...

Solution 4 - Ruby

Well...

@@secret = 'xxx'.freeze

kind of works.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDMisenerView Question on Stackoverflow
Solution 1 - RubyRenato ZannonView Answer on Stackoverflow
Solution 2 - RubyharaldView Answer on Stackoverflow
Solution 3 - Rubysepp2kView Answer on Stackoverflow
Solution 4 - RubyAnonymousView Answer on Stackoverflow