问题描述
我是 ruby 的新手,来自 php 背景,但我没有点击.
I'm pretty new to ruby, coming from a php background, but something is not clicking with me.
所以,假设我有一个 Ruby on Rails 应用程序,并且我正在像这样对我的 API 进行版本控制:
So, let's say I have a Ruby on Rails application and I am versioning my API like so:
app
|_controllers
|_api
| |_v1
| | |_application_controller.rb
| | |_user_controller.rb
| |_application_controller.rb
|_application_controller.rb
同类结构同
# Versioned API V1 app controller
module Api
module V1
class ApplicationController
end
end
end
# Versioned API app controller
module Api
class ApplicationController
end
end
# Root app controller
class ApplicationController
end
#The code in question
module Api
module V1
class UserController < ApplicationController
end
end
end
所以问题是,ruby 是否会寻找 Api::V1::ApplicationController
、Api::ApplicationController
或 ApllicationController
来扩展?
So the question is, does ruby look for Api::V1::ApplicationController
, Api::ApplicationController
, or ApllicationController
for extending?
<ApplicationController
寻找它自己的命名空间,除非我指定 Api::ApplicationController
?如果是这样,我如何指定根?
Does the < ApplicationController
look for it's own namespace unless I specify Api::ApplicationController
? If so, how do I specify the root one?
推荐答案
使用时
#The code in question
module Api
module V1
class UserController < ApplicationController
end
end
end
ApplicationController
定义将在 Api::V1
中搜索,如果在 Api
中未找到,则在根命名空间中未找到.
ApplicationController
definition will be searched in Api::V1
then if not found in Api
then if not found in the root namespace.
我同意这可能会造成混淆,这就是为什么我倾向于使用像这样的绝对路径:::ApplicationController
I agree it could be confusing, that's why I tend to use absolute paths like so: ::ApplicationController
如果我需要 Api::ApplicationController
,我会写 ::Api::ApplicationController
If ever I'd need Api::ApplicationController
, I'd write ::Api::ApplicationController
基本上 ::
告诉 ruby 从根命名空间开始,而不是从代码所在的位置开始.
Basically the ::
tells ruby to start from the root namespace and not from where the code lives.
旁注
请注意,Rails 开发模式中存在恶性案例.为了获得速度,加载了严格的最小值.然后 Rails 在需要时查找类定义.
Be aware that there are vicious cases in Rails development mode. In order to gain speed, the strict minimum is loaded. Then Rails looks for classes definitions when needed.
但这有时会失败的大例子,当你说 ::User
已经加载,然后寻找 ::Admin::User
.Rails 不会寻找它,它会认为 ::User
可以解决问题.
But this sometimes fails big time example, when you have say ::User
already loaded, and then look for ::Admin::User
. Rails would not look for it, it will think ::User
does the trick.
这可以在您的代码中使用 require_dependency
语句来解决.速度是有代价的:)
This can be solved using require_dependency
statements in your code. Speed has a cost :)
这篇关于Ruby 命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!