summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorLin Jen-Shin (godfat) <godfat@godfat.org>2017-11-13 15:27:30 +0000
committerRémy Coutable <remy@rymai.me>2017-11-13 15:27:30 +0000
commit258bf3e187538bd326491e5d1b25a0511fbd96a1 (patch)
tree366d7dfbd59ce1e64ec46eb98ea36c83317d02df /lib
parent4a1e8188f96744103e51263c9bdc071c8e088690 (diff)
downloadgitlab-ce-258bf3e187538bd326491e5d1b25a0511fbd96a1.tar.gz
Add Gitlab::Utils::StrongMemoize
Diffstat (limited to 'lib')
-rw-r--r--lib/api/api_guard.rb8
-rw-r--r--lib/gitlab/utils/strong_memoize.rb31
2 files changed, 36 insertions, 3 deletions
diff --git a/lib/api/api_guard.rb b/lib/api/api_guard.rb
index b9c7d443f6c..c1c0d344917 100644
--- a/lib/api/api_guard.rb
+++ b/lib/api/api_guard.rb
@@ -42,6 +42,8 @@ module API
# Helper Methods for Grape Endpoint
module HelperMethods
+ include Gitlab::Utils::StrongMemoize
+
def find_current_user!
user = find_user_from_access_token || find_user_from_warden
return unless user
@@ -52,9 +54,9 @@ module API
end
def access_token
- return @access_token if defined?(@access_token)
-
- @access_token = find_oauth_access_token || find_personal_access_token
+ strong_memoize(:access_token) do
+ find_oauth_access_token || find_personal_access_token
+ end
end
def validate_access_token!(scopes: [])
diff --git a/lib/gitlab/utils/strong_memoize.rb b/lib/gitlab/utils/strong_memoize.rb
new file mode 100644
index 00000000000..a2ac9285b56
--- /dev/null
+++ b/lib/gitlab/utils/strong_memoize.rb
@@ -0,0 +1,31 @@
+module Gitlab
+ module Utils
+ module StrongMemoize
+ # Instead of writing patterns like this:
+ #
+ # def trigger_from_token
+ # return @trigger if defined?(@trigger)
+ #
+ # @trigger = Ci::Trigger.find_by_token(params[:token].to_s)
+ # end
+ #
+ # We could write it like:
+ #
+ # def trigger_from_token
+ # strong_memoize(:trigger) do
+ # Ci::Trigger.find_by_token(params[:token].to_s)
+ # end
+ # end
+ #
+ def strong_memoize(name)
+ ivar_name = "@#{name}"
+
+ if instance_variable_defined?(ivar_name)
+ instance_variable_get(ivar_name)
+ else
+ instance_variable_set(ivar_name, yield)
+ end
+ end
+ end
+ end
+end