views:

69

answers:

3

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
+2  A: 

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...

sepp2k
Thanks...Seems obvious in hindsight.
DMisener
+1  A: 

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.

harald
Perhaps a little meta-programming would make this more palatable.
DMisener
I thought about it a little longer and then realized the above approach doesn't make the constant available to instance methods so I think I'll stick with @@var approach.
DMisener
A: 

Well...

@@secret = 'xxx'.freeze

kind of works.

Anonymous