summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMichael Kozono <mkozono@gmail.com>2018-09-20 11:49:58 -0700
committerMichael Kozono <mkozono@gmail.com>2018-09-24 12:11:26 -0700
commit45cf64c827270d66a88d483bb3f9043a90301255 (patch)
treeb71d4455decb58e5d429b8e5299896a70fc7c20a /lib
parent00bb83f7fc6d52583d56fb0f0ea4c9d951535b52 (diff)
downloadgitlab-ce-45cf64c827270d66a88d483bb3f9043a90301255.tar.gz
Use a null object with RequestStore
Makes it easier and safer to use RequestStore because you don't need to check `RequestStore.active?` before using it. You just have to use `Gitlab::SafeRequestStore` instead.
Diffstat (limited to 'lib')
-rw-r--r--lib/gitlab/null_request_store.rb41
-rw-r--r--lib/gitlab/safe_request_store.rb23
2 files changed, 64 insertions, 0 deletions
diff --git a/lib/gitlab/null_request_store.rb b/lib/gitlab/null_request_store.rb
new file mode 100644
index 00000000000..8db331dcb9f
--- /dev/null
+++ b/lib/gitlab/null_request_store.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+# Used by Gitlab::SafeRequestStore
+module Gitlab
+ # The methods `begin!`, `clear!`, and `end!` are not defined because they
+ # should only be called directly on `RequestStore`.
+ class NullRequestStore
+ def store
+ {}
+ end
+
+ def active?
+ end
+
+ def read(key)
+ end
+
+ def [](key)
+ end
+
+ def write(key, value)
+ value
+ end
+
+ def []=(key, value)
+ value
+ end
+
+ def exist?(key)
+ false
+ end
+
+ def fetch(key, &block)
+ yield
+ end
+
+ def delete(key, &block)
+ yield(key) if block_given?
+ end
+ end
+end
diff --git a/lib/gitlab/safe_request_store.rb b/lib/gitlab/safe_request_store.rb
new file mode 100644
index 00000000000..4e82353adb6
--- /dev/null
+++ b/lib/gitlab/safe_request_store.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module SafeRequestStore
+ NULL_STORE = Gitlab::NullRequestStore.new
+
+ class << self
+ # These methods should always run directly against RequestStore
+ delegate :clear!, :begin!, :end!, :active?, to: :RequestStore
+
+ # These methods will run against NullRequestStore if RequestStore is disabled
+ delegate :read, :[], :write, :[]=, :exist?, :fetch, :delete, to: :store
+ end
+
+ def self.store
+ if RequestStore.active?
+ RequestStore
+ else
+ NULL_STORE
+ end
+ end
+ end
+end