在使用 rswag 进行 API 文档测试时,可以通过在 config/initializers/rswag.rb
文件中配置全局参数来避免在每个 rswag 响应块中调用参数。以下是一个示例解决方法:
# config/initializers/rswag.rb
# 定义全局参数
Swagger::Docs::Config.base_api_controller = ActionController::API
# 添加全局参数
Swagger::Docs::Config.register_apis({
'1.0' => {
# 配置Swagger文档的基本信息
api_extension_type: :json,
api_file_path: 'public/api/v1',
base_path: 'http://localhost:3000',
clean_directory: true,
attributes: {
info: {
title: 'API V1',
description: 'API V1 文档',
contact: 'admin@example.com',
license: 'MIT',
licenseUrl: 'https://opensource.org/licenses/MIT'
}
}
}
})
在上述示例中,我们配置了一个全局参数并注册了一个 API 版本。在每个 rswag 响应块中不再需要调用参数,因为 rswag 会自动使用全局参数来生成 API 文档。