ruby - 有没有办法在我的 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
解决方案
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
推荐阅读
- java - Bundle 在第三个活动中为空
- ruby-on-rails - 在模型中交叉引用时,rails 包括 has_many through
- android - 在没有用户输入的情况下对移动的原生地图做出反应
- ssl - 旧客户端的 SSL 证书和具有相同 pub/private 密钥的新证书
- mysql - 编写两条不同的 SQL 语句,生成如下表
- reactjs - 我想使用 Algolia 按 SKU 获取产品
- python - 多处理队列的 100% 负载
- jetty - 是否可以在 ConnectHandler 上使用过滤器?
- sql - SQL to JSON - 如何在没有列名的情况下获取查询输出,然后将两列放在一起
- mysql - 通过 Shell 脚本输入 MySQL 密码