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

wf82jlnq  于 2023-02-03  发布在  Ruby
关注(0)|答案(5)|浏览(121)

在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
i1icjdpr

i1icjdpr1#

从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
zvokhttg

zvokhttg2#

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

def self.secret
  'xxx'
end

private_class_method :secret

这使得它可以在类的所有示例内访问,但不能在类的外部访问。

w7t8yxp5

w7t8yxp53#

您可以使用@@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

当然,ruby不会强制@@secret的恒定性,但是ruby一开始就很少强制恒定性,所以......

cgfeq70w

cgfeq70w4#

好吧...

@@secret = 'xxx'.freeze

挺管用的。

8yparm6h

8yparm6h5#

你可以从字面上把它作为一个私有方法放在首位🤷🏼‍♂️

class Person
  def SECRET
    'xxx'
  end

  def show_secret
    puts SECRET
  end
end

Person::SECRET    # Error: No such constant
Person.SECRET     # Error: No such method
Person.new.SECRET # Error: Call private method
person.new.show_secret # prints "xxx"

相关问题