如何在Ruby中创建私有类常量

DMi*_*ner 38 ruby access-specifier class-constants

在Ruby中,如何创建私有类常量?(即在课堂内可见但不在课堂外可见的)

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
Run Code Online (Sandbox Code Playgroud)

Ren*_*non 147

从ruby 1.9.3开始,你有Module#private_constant方法,这似乎正是你想要的:

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
Run Code Online (Sandbox Code Playgroud)


har*_*ald 12

您还可以将常量更改为类方法:

def self.secret
  'xxx'
end

private_class_method :secret
Run Code Online (Sandbox Code Playgroud)

这使得它可以在类的所有实例中访问,但不能在外部访问.


sep*_*p2k 9

您可以使用@@ class_variable而不是常量,它始终是私有的.

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
Run Code Online (Sandbox Code Playgroud)

当然,ruby将无法执行@@ secret的常量,但ruby在开始时执行常量方面做的很少,所以...