Ruby命名空间 [英] Ruby namespacing
问题描述
我是红宝石的新手,来自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?
除非我指定Api::ApplicationController
,否则< 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
在Api::V1
中搜索
ApplicationController
定义,然后在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
基本上::
告诉ruby从根名称空间开始,而不是从代码所在的地方开始.
Basically the ::
tells ruby to start from the root namespace and not from where the code lives.
边注
Sidenote
请注意,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命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!