【问题标题】:Change view template by API version on Grape and Rails通过 Grape 和 Rails 上的 API 版本更改视图模板
【发布时间】:2026-02-03 13:00:01
【问题描述】:

我正在 Ruby on Rails 4.1 上使用 Grape gem 构建 Web API,并使用它们的“版本”功能。

这里是示例代码。

# app/api/api.rb
class API < Grape::API
  prefix 'api'
  format :json
  formatter :json, Grape::Formatter::Rabl
  default_format :json

  mount V1::Root
end

# app/api/v1/root.rb
module V1
  class Root < Grape::API
    version 'v1'
    resource :users, rabl: "users" do
      get '/' do
        @users = User.all
      end
    end
  end
end

# config/routes.rb
mount API => "/"

使用这些代码,app/views/api/users.rabl 用于根据http://localhost:3000/api/v1/users 的请求查看模板。

我想在app/views/api/v1 中使用模板来处理v1 请求。有什么办法吗?

当前

  • /api/v1/users -> app/views/api/users.rabl
  • /api/v2/users -> app/views/api/users.rabl

想要

  • /api/v1/users -> app/views/api/v1/users.rabl
  • /api/v2/users -> app/views/api/v2/users.rabl

【问题讨论】:

  • 我正在寻找一些很棒的解决方案,但似乎 rabl-grape gem native 不支持葡萄版本,也许你可以尝试:'resource :users, rabl: "v1/users" do'。 ..我不确定它是否会起作用,因为我现在无法测试它..
  • 谢谢 Jan,您的解决方案是切换视图版本的一种方法。如果没有其他解决方案,我会采取这种方式。
  • 你最终得到结果了吗?
  • 是的,最后我选择了 Jan 的方式。

标签: ruby-on-rails api versioning grape grape-api


【解决方案1】:

我正在使用葡萄实体:https://github.com/intridea/grape-entity

所以我在 v1 文件夹上创建了一个名为 entities 的目录

例如: api/v1/entities/token_response_entity.rb

module ExampleAPI::V1::Entities
  class TokenResponseEntity < Grape::Entity
    expose :token , documentation: { type: 'string', desc: 'Token String' }
  end
end

所以当我需要展示时,我只需要使用:

present tokens, with: ExampleAPI::V1::Entities::TokenResponseEntity

【讨论】:

    【解决方案2】:

    我终于走上了简的路。

    resource :users, rabl: "v1/users" do
    

    【讨论】: