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
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
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
定数をクラス メソッドに変更することもできます。
def self.secret
'xxx'
end
private_class_method :secret
これにより、クラスのすべてのインスタンス内でアクセスできるようになりますが、外部ではアクセスできません。
定数の代わりに、常にプライベートな @@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 は最初から不変を強制することはほとんどありません。
上手...
@@secret = 'xxx'.freeze
一種の作品。