Added return_with macro to break response in the middle of the block.

This commit is contained in:
Fatih Kadir Akın 2016-03-30 00:48:58 +03:00
parent 7b1bc43a41
commit 8110788a41
3 changed files with 41 additions and 0 deletions

View file

@ -34,4 +34,37 @@ describe "Macros" do
config.logger.should be_a(CustomLogHandler) config.logger.should be_a(CustomLogHandler)
end end
end end
describe "#return_with" do
it "can break block with return_with macro" do
get "/non-breaking" do |env|
"hello"
"world"
end
request = HTTP::Request.new("GET", "/non-breaking")
client_response = call_request_on_app(request)
client_response.status_code.should eq(200)
client_response.body.should eq("world")
get "/breaking" do |env|
return_with env, 404, "hello"
"world"
end
request = HTTP::Request.new("GET", "/breaking")
client_response = call_request_on_app(request)
client_response.status_code.should eq(404)
client_response.body.should eq("hello")
end
it "can break block with return_with macro using default values" do
get "/" do |env|
return_with env
"world"
end
request = HTTP::Request.new("GET", "/")
client_response = call_request_on_app(request)
client_response.status_code.should eq(200)
client_response.body.should eq("")
end
end
end end

View file

@ -155,4 +155,5 @@ describe "Kemal::RouteHandler" do
client_response.status_code.should eq(302) client_response.status_code.should eq(302)
client_response.headers.has_key?("Location").should eq(true) client_response.headers.has_key?("Location").should eq(true)
end end
end end

View file

@ -15,6 +15,12 @@ macro render(filename, *args)
Kilt.render({{filename}}, {{*args}}) Kilt.render({{filename}}, {{*args}})
end end
macro return_with(env, status_code = 200, response = "")
{{env}}.response.status_code = {{status_code}}
{{env}}.response.print {{response}}
next
end
def add_handler(handler) def add_handler(handler)
Kemal.config.add_handler handler Kemal.config.add_handler handler
end end
@ -46,6 +52,7 @@ def logger(logger)
Kemal.config.add_handler logger Kemal.config.add_handler logger
end end
def serve_static(status) def serve_static(status)
Kemal.config.serve_static = status Kemal.config.serve_static = status
end end