首页 > 解决方案 > 如何在 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?

标签: ruby-on-rails

解决方案


在这种情况下,应该使用合并注入:

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

推荐阅读