Rails 中的受保护和私有方法 [英] Protected and private methods in Rails

查看:58
本文介绍了Rails 中的受保护和私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 中的方法可见性(公共、受保护和私有方法)已在诸如 这篇博文.但是在 Ruby on Rails 中,由于框架的设置方式,它似乎与在常规 Ruby 应用程序中的情况略有不同.那么,在 Rails 模型、控制器、助手、测试等中,什么时候使用受保护或私有方法合适/不合适?

Method visibility in Ruby (public, protected, and private methods) has been well explained in places like this blog post. But in Ruby on Rails it seems slightly different than it would be in a regular Ruby application because of the way the framework is set up. So, in Rails models, controllers, helpers, tests, etc., when is/isn't it appropriate to use protected or private methods?

编辑:感谢您到目前为止的回答.我了解 Ruby 中 protected 和 private 的概念,但我正在寻找更多关于在 Rails 应用程序的各个部分(模型、控制器、助手、测试)的上下文中使用这些类型的可见性的典型方式的解释.例如,公共控制器方法是动作方法,应用控制器中的受保护方法用于需要多个控制器访问的辅助方法"等.

Edit: Thanks for the answers so far. I understand the concept of protected and private in Ruby, but I'm looking more for an explanation of the typical way those types of visibility are used within the context of the various pieces of a Rails app (models, controllers, helpers, tests). For example, public controller methods are action methods, protected methods in the application controller are used for "helper methods" that need to be accessed by multiple controllers, etc.

推荐答案

对于模型,其思想是公共方法是类的公共接口.公共方法旨在供其他对象使用,而受保护/私有方法则对外部隐藏.

For models, the idea is that the public methods are the public interface of the class. Public methods are intended to be used by other objects, while protected/private methods are to be hidden from the outside.

这与其他面向对象语言的做法相同.

This is the same practice as in other object-oriented languages.

对于 controllers 和 测试,请随心所欲.控制器和测试类都只被框架实例化和调用(是的,我知道理论上你可以从视图中获取控制器,但如果你这样做,无论如何都会有些奇怪).因为没有人会直接创造这些东西,所以没有什么可以保护"的.

For controllers and tests, just do as you please. Both controller and test classes are only instantiated and called by the framework (yes, I know you can theoretically get the controller from the view, but if you do that, something is strange anyway). Since no one will ever create those things directly, there's nothing to "protect" against.

附录/更正:对于控制器,您应该将帮助器"方法标记为 protected 私有,并且只有操作本身应该是公开的.该框架永远不会将任何传入的 HTTP 调用路由到非公开的操作/方法,因此您的辅助方法应该以这种方式受到保护.

Addendum/Correction: For controllers, you should mark the "helper" methods as protected private, and only the actions themselves should be public. The framework will never route any incoming HTTP calls to actions/methods that are not public, so your helper methods should be protected in that way.

对于助手来说,方法是受保护的还是私有的没有区别,因为它们总是被直接"调用.

For helpers it will make no difference if a method is protected or private, since they are always called "directly".

当然,如果能让您更容易理解,您可以在所有这些情况下标记受保护的内容.

You can mark stuff protected in all those cases if it makes things easier for you to understand, of course.

这篇关于Rails 中的受保护和私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆