ruby-on-rails - 如何在 def 函数之外在 Rails 中使用请求?
问题描述
在这个源代码块中,我想basePath
为不同的环境域进行设置。例如,这些:
class ApidocsController < ApplicationController
include Swagger::Blocks
BASE_PATH = request.original_url.include?("def.com/ghi") ? '/ghi/' : '/'
swagger_root do
┆ key :swagger, '2.0'
┆ info do
┆ ┆ key :version, '1.0.0'
┆ ┆ key :title, 'Demo API'
┆ ┆ key :description, 'Demo API'
┆ ┆ contact do
┆ ┆ ┆ key :name, 'Demo'
┆ ┆ end
┆ end
┆ key :host, ENV['HOST']
┆ key :basePath, BASE_PATH
┆ key :consumes, ['application/json']
┆ key :produces, ['application/json']
end
# A list of all classes that have swagger_* declarations.
SWAGGERED_CLASSES = [
┆ PostController,
┆ self,
].freeze
def index
┆ render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES)
end
end
但导致错误:
ActionController::RoutingError (undefined local variable or method `request' for ApidocsController:Class\nDid you mean? require)
似乎request
只在一个def
函数中起作用。但是在这种情况下,如何检查 original_url 以设置不同的 basePath?
解决方案
在这种情况下,应该使用合并注入:
https://github.com/fotinakis/swagger-blocks/blob/master/README.md#overriding-attributes
def index
base_path = request.original_url.include?("def.com/ghi") ? '/ghi/' : '/'
render json: Swagger::Blocks.build_root_json(SWAGGERED_CLASSES).merge({basePath: base_path})
end
推荐阅读
- bash - 为什么这个两行 bash 提示符会弄乱命令历史
- javascript - JavaScript 中 Reduce 方法的平均值
- php - 如何在序列中的同一插入上插入序列号?
- bash - Bash单行嵌套for循环将比较变量作为命令
- python - Python pandas数据框'SUMIF' - 标准范围与总和范围不同
- c++ - 在OpenGL的角落显示文本
- node.js - 同步 node.js 调用
- javascript - 使用 JS(和 jquery 和/或 AJAX)在 HTML 中加载 LOCAL JSON 文件;答案=不可能
- java - Java CompletableFuture 分配执行器
- c# - iTextSharp 升级到 iText7 .NET