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

如何在Ramaze框架中挂载Grape框架并配置自定义路由?

在Ramaze中挂载Grape API并自定义路由

一、基础挂载步骤

  1. 安装依赖
    执行命令安装所需gem:

    gem install ramaze grape
    
  2. 集成Grape到Ramaze项目
    在Ramaze启动文件(如app.rb或config.ru)中引入你的Grape API类,通过Rack完成挂载:

    • 若使用app.rb:
      require 'ramaze'
      require './api' # 引入你的Api类文件
      
      # 挂载Grape API到指定路径
      Ramaze.middleware.use Rack::Mount do |map|
        map.mount Api.new, at: '/api'
      end
      
      Ramaze.start
      
    • 若使用config.ru(适配Rack部署):
      require 'ramaze'
      require './api'
      
      run Rack::URLMap.new(
        '/' => Ramaze.application, # 保留Ramaze原有业务路由
        '/api' => Api.new          # 将Grape API挂载到/api路径
      )
      

二、自定义路由配置

有两种方式实现路由自定义:

1. 在Grape API类内部调整

直接修改Api类,设置全局前缀、资源子路由或独立路由:

require 'grape'

class Api < Grape::API 
  prefix '/v1'                  # 给所有API路由添加/v1前缀
  format :json 

  # 资源型路由
  resources :articles do 
    get do                      # 访问路径:/api/v1/articles
      {hello: 'hello world!'}
    end

    get ':id' do                # 访问路径:/api/v1/articles/:id
      {article_id: params[:id], content: 'Single article detail'}
    end
  end 

  # 独立自定义路由
  get '/greet' do               # 访问路径:/api/v1/greet
    {message: 'Hello from custom route!'}
  end
end

2. 在Ramaze挂载时修改根路径

无需改动Grape代码,直接调整挂载的at参数,将整个API挂载到任意路径:

# 示例:挂载到/custom-api路径
Ramaze.middleware.use Rack::Mount do |map|
  map.mount Api.new, at: '/custom-api'
end

此时原articles路由的访问路径变为/custom-api/articles。

三、验证测试

启动Ramaze后,用curl或浏览器访问对应路径验证:

curl http://localhost:7000/api/articles
# 预期返回:{"hello":"hello world!"}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:46:26