2013-03-25 41 views
0

什么是保护属性的最佳方式?请参阅以下几点:保护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 
+0

我认为'受保护的'关键字做你需要的。 – 2013-03-25 07:02:59

回答

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例如值。

+0

或'私人',如果你不想让孩子课程访问它。 – toch 2013-03-25 10:03:25

+0

是的,编辑我的答案,thx。 – Intrepidd 2013-03-25 10:04:55

2

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

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

+0

感谢您的注意。我最终通过具有相同名称的方法覆盖object.sensitive_data的访问权限,然后保护它。 – 2013-03-25 19:01:17