Since Ruby 2.0 or so, it's been possible to make a constant private using private_constant
, resulting in an error if the constant is used directly outside the declaring module.
从Ruby 2.0开始,使用private_constant可以创建一个常量私有,如果直接在声明模块之外使用常量,则会导致错误。
However, constants
and const_defined?
still return private constants, and const_get
allows access to them. Is there a way to programmatically identify private constants and filter them out at run time?
但是,常量和const_defined?仍然返回私有常量,const_get允许访问它们。有没有办法以编程方式识别私有常量并在运行时过滤掉它们?
(Note: What does Module.private_constant do? Is there a way to list only private constants? and its answer don't specifically address this case, but rather the reverse (how to list only private constants).)
(注意:Module.private_constant有什么作用?有没有办法只列出私有常量?它的答案并没有专门解决这种情况,而是反过来(如何只列出私有常量)。)
Update: It looks as though in Ruby 1.9 and 2.0, constants
did include only public constants. As of 2.1, the no-arg constants
still includes only public constants, but setting inherit
to false
with constants(false)
(i.e., list only constants defined in this module, not in its ancestor modules) has the side effect of exposing the private constants.
更新:看起来好像在Ruby 1.9和2.0中,常量确实只包含公共常量。从2.1开始,no-arg常量仍然只包含公共常量,但是使用常量(false)将inherit设置为false(即,仅列出此模块中定义的常量,而不是其祖先模块中的常量)具有暴露私有的副作用常量。
1 个解决方案
#1
4
You can identify constants by next way:
您可以通过下一个方式识别常量:
class A
C = "value"
private_constant :C
C2 = "value2"
end
A.constants #public constants
#=> [:C2]
A.constants(false) #public & private constants
#=> [:C, :C2]
A.constants(false) - A.constants #private constants
#=> [:C]
#1
4
You can identify constants by next way:
您可以通过下一个方式识别常量:
class A
C = "value"
private_constant :C
C2 = "value2"
end
A.constants #public constants
#=> [:C2]
A.constants(false) #public & private constants
#=> [:C, :C2]
A.constants(false) - A.constants #private constants
#=> [:C]