52

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
4

4 に答える 4

169

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
于 2012-08-09T14:09:52.943 に答える
13

定数をクラス メソッドに変更することもできます。

def self.secret
  'xxx'
end

private_class_method :secret

これにより、クラスのすべてのインスタンス内でアクセスできるようになりますが、外部ではアクセスできません。

于 2010-05-20T13:22:50.303 に答える
11

定数の代わりに、常にプライベートな @@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 は最初から不変を強制することはほとんどありません。

于 2010-05-20T13:19:04.613 に答える
0

上手...

@@secret = 'xxx'.freeze

一種の作品。

于 2010-05-20T14:41:57.257 に答える