Ruby命名空间 [英] Ruby namespacing

查看:152
本文介绍了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::ApplicationControllerApi::ApplicationControllerApllicationController进行扩展吗?

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中找不到,然后在根名称空间中找不到.

ApplicationControllerdefinition 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屋!

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