保护ruby对象属性不被访问

时间:2013-03-25 06:59:26

标签: ruby-on-rails ruby

保护属性的最佳方法是什么?请参阅以下内容:

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

2 个答案:

答案 0 :(得分: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来检索该值。

答案 1 :(得分:2)

无法阻止某人访问该数据。无论您是否愿意,元编程都会暴露您班级的所有内部。

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