Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGitLab Bot <gitlab-bot@gitlab.com>2020-01-03 18:08:33 +0300
committerGitLab Bot <gitlab-bot@gitlab.com>2020-01-03 18:08:33 +0300
commit511e761b41b81484c85e3d125f45873ce38e9201 (patch)
tree6bb98a6356de6e1d736951d2eef6ec83e6aa3dd2 /lib/gitlab/utils
parent4247e67be1faa9d52691757dad954a7fa63e8bfe (diff)
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'lib/gitlab/utils')
-rw-r--r--lib/gitlab/utils/lazy_attributes.rb45
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/gitlab/utils/lazy_attributes.rb b/lib/gitlab/utils/lazy_attributes.rb
new file mode 100644
index 00000000000..79f3a7dcb53
--- /dev/null
+++ b/lib/gitlab/utils/lazy_attributes.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module Utils
+ module LazyAttributes
+ extend ActiveSupport::Concern
+ include Gitlab::Utils::StrongMemoize
+
+ class_methods do
+ def lazy_attr_reader(*one_or_more_names, type: nil)
+ names = Array.wrap(one_or_more_names)
+ names.each { |name| define_lazy_reader(name, type: type) }
+ end
+
+ def lazy_attr_accessor(*one_or_more_names, type: nil)
+ names = Array.wrap(one_or_more_names)
+ names.each do |name|
+ define_lazy_reader(name, type: type)
+ define_lazy_writer(name)
+ end
+ end
+
+ private
+
+ def define_lazy_reader(name, type:)
+ define_method(name) do
+ strong_memoize("#{name}_lazy_loaded") do
+ value = instance_variable_get("@#{name}")
+ value = value.call if value.respond_to?(:call)
+ value = nil if type && !value.is_a?(type)
+ value
+ end
+ end
+ end
+
+ def define_lazy_writer(name)
+ define_method("#{name}=") do |value|
+ clear_memoization("#{name}_lazy_loaded")
+ instance_variable_set("@#{name}", value)
+ end
+ end
+ end
+ end
+ end
+end