简体   繁体   English

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

[英]How to I make private class constants in Ruby

In Ruby how does one create a private class constant?在 Ruby 中,如何创建私有常量 class? (ie one that is visible inside the class but not outside) (即在 class 内部可见但在外部不可见的一个)

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

Starting on ruby 1.9.3, you have the Module#private_constant method, which seems to be exactly what you wanted:从 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

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.这使得它可以在类的所有实例中访问,但不能在外部访问。

Instead of a constant you can use a @@class_variable, which is always private.您可以使用 @@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

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...当然,ruby 不会强制执行@@secret 的恒定性,但是 ruby​​ 开始时几乎没有强制执行恒定性,所以......

Well...好...

@@secret = 'xxx'.freeze

kind of works.种作品。

You can just literally make it a private method in the first place ♂️首先,您可以直接将其设为私有方法 ♂️

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM