[英]Ruby namespacing
我是非常新的ruby,來自php背景,但有些東西沒有點擊我。
所以,假設我有一個Ruby on Rails應用程序,我正在對我的API進行版本控制:
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
進行擴展?
除非我指定Api::ApplicationController
否則< ApplicationController
是否會查找它自己的命名空間? 如果是這樣,我如何指定根目錄?
當你使用
#The code in question
module Api
module V1
class UserController < ApplicationController
end
end
end
將在Api::V1
搜索ApplicationController
定義,如果在Api
找不到,則在根命名空間中找不到。
我同意它可能會令人困惑,這就是我傾向於使用絕對路徑的原因::ApplicationController
如果我需要Api::ApplicationController
,我會編寫::Api::ApplicationController
基本上, ::
告訴ruby從根命名空間開始,而不是從代碼所在的位置開始。
邊注
請注意,Rails開發模式中存在惡意案例。 為了獲得速度,加載嚴格的最小值。 然后Rails在需要時查找類定義。
但是這有時會失敗大時間的例子,當你說::User
已經加載,然后尋找::Admin::User
。 Rails不會尋找它,它會認為::User
做到這一點。
這可以使用代碼中的require_dependency
語句來解決。 速度有成本:)
我寧願建議不要在命名空間中編寫ApplicationController
,我建議遵循以下內容
注意:如果你正在構建專業的api,那么讓Api::V1::BaseController
從ActionController::Base
繼承總是好的,盡管我給你的具體案例提供了解決方案
參考這篇文章: 像專業人士一樣實現Rails API
1)以app / controllers / application_controller.rb中的常規方式定義應用程序控制器
class ApplicationController < ActionController::Base
end
2)在app / controllers / api / v1 / base_controller.rb中定義基本api控制器即Api :: V1 :: BaseController,它將繼承自ApplicationController
(你的情況)
class Api::V1::BaseController < ApplicationController
end
3)在app / controllers / api / v1 / users_controller.rb中定義api控制器,如Api::V1::UsersController
,它將繼承自Api :: V1 :: BaseController
class Api::V1::UsersController < Api::V1::BaseController
end
4)添加所有后續控制器,如Api::V1::UsersController
(步驟3)
然后路由將在config / routes.rb中包含名稱空間路由
namespace :api do
namespace :v1 do
resources :users do
#user routes goes here
end
# any new resource routing goes here
# resources :new_resource do
# end
end
end
您應該查看指南以了解路由: http : //guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
我認為這個問題非常類似於:
由於短缺:
Rails將通過該文件夾自動檢測命名空間。 所以你不需要將它附加到名稱:
這篇博客文章解釋得很好:
http://blog.makandra.com/2014/12/organizing-large-rails-projects-with-namespaces/
假設我們有一個發票類,每張發票可以有多個發票項目:
class Invoice < ActiveRecord::Base has_many :items end class Item < ActiveRecord::Base belongs_to :invoice end
顯然,Invoice是Items的組合,如果沒有包含Invoice,則Item不能生效。 其他類可能與Invoice交互而不與Item交互。 因此,讓它通過將它嵌套到Invoice命名空間中來使Item脫離。 這涉及將類重命名為Invoice :: Item並將源文件移動到app / models / invoice / item.rb:
class Invoice::Item < ActiveRecord::Base belongs_to :invoice end
同樣適用於控制器和視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.