Added support for magic param _method just like Rails, Sinatra.

Following are the changes made in this commit:

- Added support for magic param `_method` just like Rails, Sinatra
etc.. Browsers which don't support `PUT`, `PATCH` and `DELETE` methods
can simulate them by sending `method` param in request body.

- The default Content-Type to parse request body submitted via forms
etc. is `application/x-www-form-urlencoded`. But if we send Ajax
request in Chrome ($.post) then by-default Content-Type is set to
`application/x-www-form-urlencoded; charset utf-8` which was not
getting matched. I changed the code from `==` to match against a
regular expression using `=~`.

- Print name and color of overridden HTTP method via Logger instead of
printing name and color or request's incoming HTTP method.

Making necessary changes as pointed by @sdogruyol

- Changed method name from`is_override_method_valid?` to
`override_method_valid?`.

- Refactored `if` condition in `override_method_valid?`.
This commit is contained in:
Imran Latif 2015-12-03 00:57:23 +05:00
parent dfea8df0f7
commit c42f1f88e9
4 changed files with 73 additions and 2 deletions

View file

@ -120,4 +120,51 @@ describe "Kemal::Handler" do
response.status_code.should eq 500
response.body.includes?("Exception").should eq true
end
it "checks for _method param in POST request to simulate PUT" do
kemal = Kemal::Handler.new
kemal.add_route "PUT", "/", do |env|
"Hello World from PUT"
end
request = HTTP::Request.new(
"POST",
"/",
body: "_method=PUT",
headers: HTTP::Headers{"Content-Type": "application/x-www-form-urlencoded"}
)
response = kemal.call(request)
response.body.should eq("Hello World from PUT")
end
it "checks for _method param in POST request to simulate PATCH" do
kemal = Kemal::Handler.new
kemal.add_route "PATCH", "/", do |env|
"Hello World from PATCH"
end
request = HTTP::Request.new(
"POST",
"/",
body: "_method=PATCH",
headers: HTTP::Headers{"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}
)
response = kemal.call(request)
response.body.should eq("Hello World from PATCH")
end
it "checks for _method param in POST request to simulate DELETE" do
kemal = Kemal::Handler.new
kemal.add_route "DELETE", "/", do |env|
"Hello World from DELETE"
end
json_payload = {"_method": "DELETE"}
request = HTTP::Request.new(
"POST",
"/",
body: json_payload.to_json,
headers: HTTP::Headers{"Content-Type": "application/json"}
)
response = kemal.call(request)
response.body.should eq("Hello World from DELETE")
end
end