如何阅读 Rails 示例项目的源代码? [英] How to read source code of Rails sample project?
问题描述
推荐阅读示例项目的源代码,例如 Beast 和 Bort,作为学习 Rails 的好方法.但是我发现自己在阅读这些项目的源代码时迷失了方向,因为包含的插件可能会在没有任何提示的情况下引入一些奇怪的代码,例如 "require"
或 "include"
.可以分享一下你的 Rails 代码阅读经验吗?非常感谢.
Reading source code of sample projects, such as Beast and Bort, are recommended as a good way to learn rails. But I found myself getting lost in reading source code of these projects, cause the included plugins might bring in some strange code without any hint, such as "require"
or "include"
. Could you share your rails code reading experience? Lots of thanks ahead.
推荐答案
在学习使用 Rails 时,需要了解的最重要的事情之一是它如何加载您编写的代码.假设您在 app/controllers/demo/sub 目录中有一个 HelloController.如果你生成了这个控制器,它会有正确的名字 Demo::Sub::HelloController.
When learning to use rails, one of the most important things to know is how it loads the code you've written. Let's say you have a HelloController in the app/controllers/demo/sub directory. If you generated this controller, it will have the correct name of Demo::Sub::HelloController.
当你的路由告诉 rails 寻找 "demo/sub/hello" 时,它会被翻译成控制器的全名 (Demo::Sub::HelloController),他们将尝试调用哪个 rails.Ruby 找不到这个类并调用 const_missing ,这使得 rails 将名称转换为文件,在这种情况下是 demo/sub/hello_controller (:: =/,除了 first = _ 之外的大写,在下划线方法下查找 Inflections ).然后 Rails 需要这个文件并检查正确的类定义.
When your route tells rails to look for "demo/sub/hello", that is translated into the controller's full name (Demo::Sub::HelloController) which rails will they try to call. Ruby cannot find this class and calls const_missing which makes rails translate the name into a file, in this case demo/sub/hello_controller (:: = /, capitals other than first = _, look for Inflections under underscore method). Rails then requires this file and checks for the correct class definition.
Rails 在 ruby 的加载路径中添加了几个目录(app/controllers、app/models、app/helpers、lib、vendor),并且这些目录中的任何一个 demo/sub/hello_controller.rb 都可以满足要求.但是不在应用程序/控制器中的控制器需要特别注意那里的视图.
Rails adds several directories into the ruby's load path (app/controllers, app/models, app/helpers, lib, vendor) and a demo/sub/hello_controller.rb in any of these directories will satisfy the require. But controllers not in app/controllers will need special care for there views.
此外,这适用于命名空间,只有它会查找目录.因此,引用 Demo::Sub 将查找 demo/sub 目录.这允许您放弃类的标准定义,因此您可以这样做
Also, this works for the namespaces, only it will look for a directory. So referencing Demo::Sub will look for the demo/sub directory. This allows you to forgo the standard definition of classes, so you can do
class Demo::Sub::HelloController < ActionController::Base
end
代替
module Demo
module Sub
class HelloController < ActionController::Base
end
end
end
这篇关于如何阅读 Rails 示例项目的源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!