有没有办法在我的 sinatra 应用程序中使用不同的 mime 类型

Is there a way to use different mime type in my sinatra app

我正在 Sinatra 中创建我的 Api,但我想使用以下路线:

/places /places.meta /places.list /users/id/places.list

我在 rails 中可以使用,但在 sinatra

中失败
  def index
    case request.format.to_sym.to_s
    when 'list'
      result = Place.single_list(parameters)
    when 'meta'
      result = @parameters.to_meta
    else
      result = Place.get_all(parameters)
    end
    render json: result, status: 200
  end

Sinatra 没有 "request format" 的 built-in 概念,因此您必须手动指定 format-aware 路由模式,Rails 会自动为您提供。

这里我使用指定为带有命名捕获的 Regexp 的路由模式:

require 'sinatra'

get /\/places(\.(?<format>meta|list))?/ do # named capture 'format'
  case params['format'] # params populated with named captures from the route pattern
  when 'list'
    result = Place.single_list(parameters)
  when 'meta'
    result = @parameters.to_meta
  else
    result = Place.get_all(parameters)
  end

  result.to_json # replace with your favourite way of building a Sinatra response
end