How to I make private class constants in Ruby

DMisener picture DMisener · May 20, 2010 · Viewed 15.6k times · Source

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

Renato Zannon picture Renato Zannon · Aug 9, 2012

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