You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails 5.2中Grape API如何定义方法读取Markdown填充desc说明

Grape 的 desc 配置块在类定义上下文执行,你之前定义的实例方法、Grape 原生 helper 都属于实例级方法,仅能在接口请求处理的逻辑上下文调用,类定义阶段调用自然会抛出 undefined method 错误。

以下是两种可行的实现方案:

方案1:单个API类内使用,直接定义类方法

直接在你需要调用的API类中定义类级别方法,类上下文可以直接调用该方法:

class V1::DonationsAPI < Grape::API
  # 定义类级别的读取方法
  def self.api_description(filename)
    # 自动拼接文档目录前缀,无需每次传全路径
    full_doc_path = Rails.root.join("app", "api", "v1", "docs", "donations_api", filename)
    # 生产环境缓存读取结果,避免重复读磁盘
    @desc_cache ||= {}
    return @desc_cache[full_doc_path] if Rails.env.production? && @desc_cache.key?(full_doc_path)

    content = File.read(full_doc_path)
    @desc_cache[full_doc_path] = content if Rails.env.production?
    content
  end

  desc '获取捐赠列表' do
    # 直接在desc块中调用类方法
    description api_description('index.md')
  end
  get :index do
    # 接口业务逻辑
  end
end

方案2:全局所有API通用,抽公共模块全局扩展

如果你需要在多个API类中使用该方法,可以抽离为公共模块,全局扩展到所有Grape API的类上下文:

  1. 新建公共模块文件 app/api/concerns/api_doc_helper.rb
module ApiDocHelper
  def api_description(filename, module_dir)
    full_doc_path = Rails.root.join("app", "api", "v1", "docs", module_dir, filename)
    @api_desc_cache ||= {}
    return @api_desc_cache[full_doc_path] if Rails.env.production? && @api_desc_cache.key?(full_doc_path)

    content = File.read(full_doc_path)
    @api_desc_cache[full_doc_path] = content if Rails.env.production?
    content
  end
end

# 全局扩展到所有Grape API类的类上下文
Grape::API.extend ApiDocHelper
  1. 任意API类中直接调用即可:
class V1::DonationsAPI < Grape::API
  desc '获取捐赠列表' do
    # 第二个参数传入对应文档的目录名
    description api_description('index.md', 'donations_api')
  end
end

注意事项

  • 上述代码默认仅在生产环境缓存文档内容,开发环境下修改Markdown文件后刷新即可看到最新内容,无需重启服务。
  • 请确保Markdown文件的读取权限配置正确,避免生产环境出现读取权限报错。

内容的提问来源于stack exchange,提问作者Ziyan Junaideen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:15:04