最近在学习Sinatra。今天遇到了关于RESTful的问题,用过Rails的各位应该都对这个不陌生了,不过重量级的Rails有内置helper帮我们在模板里生成那些东西,轻量级的Sinatra可不会,我们要自己动手。
仿照Rails,在views模板中加入了 <input type="hidden" name="_method" value="put">
,然后submit一下试试,然后发现还是被判断为一个post请求……
上网查了资料,说是如果用的是Modular风格的话,必须自己动手加入 use Rack::MethodOverride
。试了下,果然可以。
但是又觉得这个方法太傻了一点,于是又在Sinatra官网仔细晃了一圈,发现原来settings里有这一项 :method_override
,加入代码,搞定。
app.rb:
# encoding: utf-8
require "sinatra/base"
require "sinatra/contrib"
require "slim"
class RestTry < Sinatra::Base
set :method_override => true
register Sinatra::Contrib
route :get, "/" do
slim :rest, :locals => { :method => request.request_method }
end
run!
end
rest.slim :
doctype 5
html
head
meta charset="utf-8"
title Sinatra REST Trying
body
p Method: #{method}
section#get
form action="." method="get"
input type="submit" value="GET"
section#post
form action="." method="post"
input type="submit" value="POST"
section#put
form action="." method="post"
input type="hidden" name="_method" value="put"
input type="submit" value="PUT"
section#patch
form action="." method="post"
input type="submit" value="PATCH"
section#delete
form action="." method="post"
input type="submit" value="DELETE"
section#options
form action="." method="post"
input type="submit" value="OPTIONS"
section#custom
form action="." method="post"
input type="submit" value="CUSTOM"