通过将Swagger与控制器分开来清理API控制器

时间:2016-09-27 13:27:02

标签: ruby-on-rails api module swagger controllers

我正在使用Swagger作为我的rails API的UI。这意味着在我的API控制器中,我有很多swagger代码块,使我的文件难以阅读。 我正在寻找一种解决问题的方法。

这就是我所拥有的:

在我的controllers / api / v1 / stuffs_controller.rb

module Api
  module V1
    class StuffsController < BaseController
      has_scope :by_category, type: :array
      has_scope :by_stuff_type, type: :array
      has_scope :by_device_type, type: :array
      before_action :set_stuff, only: [:show, :like, :unlike, :desire, :undesire]

      swagger_controller :stuffs, 'Stuffs'    

      swagger_api :index do
        summary 'Get all the stuffs'
        param :query, :by_category, :string, :optionnal, "Category"
        param :query, :by_stuff_type, :string, :optionnal, "Stuff Type"
        param :query, :by_device_type, :string, :optionnal, "Device Type"
        param :query, :s, :array, :optionnal, "Search Terms"
      end

      def index
        render json: collection, each_serializer: Api::V1::Stuff::IndexSerializer, include: ['categories', 'users.devices', 'stuffs.categories', 'user', 'user.devices.device_model'], status: 200, root: nil
      end

    end
  end
end

对于每个控制器中的每个动作都是如此:s

我尝试创建模块来封装Swagger UI逻辑并清理一下我的控制器。这就是我提出的(不起作用):

在controllers / api / v1 / stuffs_controller.rb中

module Api
  module V1
    class StuffsController < BaseController
      include SwaggerStuffs

      has_scope :by_category, type: :array
      has_scope :by_stuff_type, type: :array
      has_scope :by_device_type, type: :array
      before_action :set_stuff, only: [:show, :like, :unlike, :desire, :undesire]

      swagger_controller :stuffs, 'Stuffs'    

      SwaggerStuffs.call_index
      def index
        render json: collection, each_serializer: Api::V1::Stuff::IndexSerializer, include: ['categories', 'users.devices', 'stuffs.categories', 'user', 'user.devices.device_model'], status: 200, root: nil
      end

    end
  end
end

然后在lib / swagger_modules / recipes_controller_module.rb中:

module SwaggerStuffs
  def self.call_index
    swagger_api :index do
      summary 'Get all the stuffs'
      param :query, :by_category, :string, :optionnal, "Category"
      param :query, :by_stuff_type, :string, :optionnal, "Stuff Type"
      param :query, :by_device_type, :string, :optionnal, "Device Type"
      param :query, :s, :array, :optionnal, "Search Terms"
    end
  end
end

当我尝试使用swagger UI或重新启动服务器时,会产生以下错误:

uninitialized constant Api::V1::StuffsController::SwaggerStuffs (NameError)

我在 config / application.rb 文件中添加了config.autoload_paths += %W(#{config.root}/lib),但出现了同样的错误。

我有什么遗失的吗? 将swagger逻辑与我的控制器分开是一个好习惯吗?

谢谢:)

0 个答案:

没有答案