从模块访问私有常量

Jos*_*ima 5 ruby

有没有办法从包含的模块访问私有常量?

这就是我想做的:

module B
  def access_private_here
    puts MY_CONST
  end
end

class A
  include B
  private
    MY_CONST = 1
end
Run Code Online (Sandbox Code Playgroud)

我知道,如果这个常数是公开的,我可以这样做self.class::MY_CONST,有什么办法可以与私人缺点相同吗?

Car*_*and 4

include B我建议这样写,这样除了重命名之外,您无需更改任何内容B

module B
  def access_private_here
    puts self.class::MY_CONST
  end
end

class A
  include B
  private
    MY_CONST = "cat"
end

A.new.access_private_here #=> "cat"
Run Code Online (Sandbox Code Playgroud)