您在 Rails 中使用过受保护的可见性吗?
坦白:我的方法只使用私有和公共可见性!
我有一种感觉,这是一件坏事。 但在 Rails 中,这似乎并不是一个问题。
有没有人在Rails中有一个例子,其中不使用受保护的可见性将是一个很大的错误?
Confession: I only use private and public visibility for my methods!
I have a feeling this is a bad thing. But in Rails it just doesn't seem to come up as an issue.
Does anyone have an example in Rails where it would be a big mistake not to use protected visibility?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新 - 请参阅下面链接到 Ruby 中
protected
/private
的真实解释。 这确实是我在爪哇时代留下的根深蒂固的偏见。 我的答案中唯一重要的部分是,不是操作的控制器方法不应该是公共的(或者至少你的路由应该保护它们)。单表继承是
protected
在模型层中发挥作用的完美示例,因为它是继承最常见的用途之一。在控制器层中,在
ApplicationController
上定义的辅助方法应标记为受保护
——如果它们是私有
,其他控制器将无法访问它们,但如果它们是公共的,Rails 会将它们视为操作。就我个人而言,我发现我比许多朋友和同事更多地使用类继承,即使在 Rails 应用程序中也是如此。 因为我经常使用它(并且是在我的 Java 时代),所以我喜欢对所有辅助方法使用
protected
,以便为想要扩展该类的任何人(通常是我自己)提供自由 —— 除非我真的很尴尬,然后我将其标记为私人
。 :)Update -- Please see the comment below that links to a true explanation of
protected
/private
in Ruby. That was a deep seated prejudice left over from my Java days, indeed. The only important part left to my answer is that controller methods that are not actions should not bepublic
(or at least your routes should protect them).Single Table Inheritance is a perfect example of when
protected
is helpful in the model tier, as it's one of the most common uses of inheritance there.In the controller tier, helper methods defined on
ApplicationController
should be marked asprotected
-- if they wereprivate
the other controllers would not be able to access them, but if they arepublic
Rails will treat them as actions.Personally, I find that I use class inheritance more than many of my friends and coworkers, even in Rails applications. Because I use it often (and coming out of my Java days), I favor
protected
for all helper methods to give freedom to anyone (usually myself) who wants to extend the class -- unless I'm really really embarrassed about one, then I mark itprivate
. :)我有 SingleTableInheritance
类 Person < AR::基础
班主任< 人
班级学生< 我
使用受保护的方法来实现学生和教师常见的私有方法:
免责声明:有像 act-as-paranoid 等插件来实现我在这里用来向您展示案例的功能,但我有更多复杂的景观,我在这里简化了以表达你的观点。
I have SingleTableInheritance
class Person < AR::base
class Teacher < Person
calss Student < Person
And I use the protected methods to implement a private method that is common for Student and Teacher:
Disclaimer: There are plugins like act-as-paranoid and other to implement the feature I use here to show you the case but I have a more complex landscape, that I have simplified here to get to your point.