From 09d82ed74b09b260d756de392d832d326b5fef28 Mon Sep 17 00:00:00 2001 From: Sdogruyol Date: Thu, 14 Jul 2016 21:56:01 +0300 Subject: [PATCH] Add context store --- spec/context_spec.cr | 30 +++++++++++++++++++++++++++++- src/kemal/context.cr | 11 +++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/spec/context_spec.cr b/spec/context_spec.cr index 8ffd7cd..e954a30 100644 --- a/spec/context_spec.cr +++ b/spec/context_spec.cr @@ -40,4 +40,32 @@ describe "Context" do client_response = call_request_on_app(request) client_response.headers["Accept-Language"].should eq "tr" end -end + + it "can store variables" do + before_get "/" do |env| + env.set "before_get", "Kemal" + env.set "before_get_int", 123 + env.set "before_get_float", 3.5 + end + + get "/" do |env| + env.set "key", "value" + { + key: env.get("key"), + before_get: env.get("before_get"), + before_get_int: env.get("before_get_int"), + before_get_float: env.get("before_get_float") + } + end + request = HTTP::Request.new("GET", "/") + io = MemoryIO.new + response = HTTP::Server::Response.new(io) + context = HTTP::Server::Context.new(request, response) + Kemal::Middleware::Filter::INSTANCE.call(context) + Kemal::RouteHandler::INSTANCE.call(context) + context.store["key"].should eq "value" + context.store["before_get"].should eq "Kemal" + context.store["before_get_int"].should eq 123 + context.store["before_get_float"].should eq 3.5 + end +end \ No newline at end of file diff --git a/src/kemal/context.cr b/src/kemal/context.cr index 7e53f88..69748fd 100644 --- a/src/kemal/context.cr +++ b/src/kemal/context.cr @@ -2,6 +2,9 @@ # information such as params, content_type e.g class HTTP::Server class Context + alias StoreTypes = Nil | String | Int32 | Float64 | Bool + getter store = {} of String => StoreTypes + def params @request.url_params ||= route_lookup.params @params ||= Kemal::ParamParser.new(@request) @@ -24,5 +27,13 @@ class HTTP::Server @session ||= Kemal::Sessions.new(self) @session.not_nil! end + + def get(name) + @store[name] + end + + def set(name, value) + @store[name] = value + end end end