Ruby namespacing

后端 未结 3 930
温柔的废话
温柔的废话 2020-12-10 05:32

I\'m pretty new to ruby, coming from a php background, but something is not clicking with me.

So, let\'s say I have a Ruby on Rails application and I am versioning m

3条回答
  •  猫巷女王i
    2020-12-10 06:03

    I would rather suggest don't write ApplicationController in namespace, I would suggest to follow following

    Note: If you are building professional api's it always good to have Api::V1::BaseController inheriting from ActionController::Base, though I am giving solution to your specific case

    Ref this post: Implementing Rails APIs like a professional

    1) Define application controller in usual way in app/controllers/application_controller.rb as

    class ApplicationController < ActionController::Base
    end 
    

    2) Define base api controller namely Api::V1::BaseController in app/controllers/api/v1/base_controller.rb which will inherit from ApplicationController (your case) like

    class Api::V1::BaseController < ApplicationController
    end 
    

    3) Define your api controllers like Api::V1::UsersController in app/controllers/api/v1/users_controller.rb which will inherit from Api::V1::BaseController

    class Api::V1::UsersController < Api::V1::BaseController
    end 
    

    4) Add all subsequent controllers like Api::V1::UsersController (step 3)

    Then routing will contain namespaces routing in 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
    

提交回复
热议问题