How to I make private class constants in Ruby

百般思念 提交于 2019-12-03 07:25:51

问题


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

回答1:


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.




回答2:


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



回答3:


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




回答4:


Well...

@@secret = 'xxx'.freeze

kind of works.



来源:https://stackoverflow.com/questions/2873903/how-to-i-make-private-class-constants-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!