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

请记住,即使这只是隐藏了 getter / setter,任何人都可以使用send例如检索值。

于 2013-03-25T09:52:54.973 回答
2

没有办法阻止某人访问该数据。无论您是否愿意,元编程都会暴露您类的几乎所有内部​​结构。

也就是说,将 get_sensitive_data 标记为 protected 或 private 至少可以防止 get_sensitive_data 方法被意外调用。

于 2013-03-25T09:52:47.397 回答