0

属性を保護するための最良の方法は何ですか?以下のポイントを参照してください。

class Document

  # no method outside this class can access this directly. If they call document.data, error should be thrown. including in any rendering 
  field sensitive_data

  # but this method can be accessed by anyone
  def get_sensitive_data
    # where I apply the right protection
  end

end
4

2 に答える 2

3

protectedキーワードを使用します。

class Document

  # but this method can be accessed by anyone
  def get_sensitive_data
    # where I apply the right protection
  end

  protected # or private if you don't want a child class accesses it (Thx @toch)

  # no method outside this class can access this directly. If they call document.data, error should be thrown. including in any rendering 
  field sensitive_data


end

これがゲッター/セッターを非表示にするだけでも、sendたとえばを使用して誰でも値を取得できることに注意してください。

于 2013-03-25T09:52:54.973 に答える
2

誰かがそのデータにアクセスするのを防ぐ方法はありません。メタプログラミングは、必要かどうかに関係なく、クラスのほとんどすべての内部を公開します。

とはいえ、get_sensitive_dataを保護またはプライベートとしてマークすると、少なくともget_sensitive_dataメソッドが誤って呼び出されるのを防ぐことができます。

于 2013-03-25T09:52:47.397 に答える