首页 > 解决方案 > 有没有办法在我的 sinatra 应用程序中使用不同的 mime 类型

问题描述

我正在 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

标签: rubysinatra

解决方案


Sinatra 没有“请求格式”的内置概念,因此您必须手动指定 Rails 自动为您提供的格式感知路由模式。

在这里,我使用指定为带有命名捕获的正则表达式的路由模式:

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

推荐阅读