2018-11-19 21:01:13 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2019-01-21 14:20:38 -05:00
|
|
|
require_dependency 'gitlab/utils'
|
|
|
|
|
2017-11-13 10:27:30 -05:00
|
|
|
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:
|
|
|
|
#
|
2017-12-11 10:38:16 -05:00
|
|
|
# include Gitlab::Utils::StrongMemoize
|
|
|
|
#
|
2017-11-13 10:27:30 -05:00
|
|
|
# def trigger_from_token
|
|
|
|
# strong_memoize(:trigger) do
|
|
|
|
# Ci::Trigger.find_by_token(params[:token].to_s)
|
|
|
|
# end
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
def strong_memoize(name)
|
2019-09-04 04:14:24 -04:00
|
|
|
if strong_memoized?(name)
|
2017-12-11 10:38:16 -05:00
|
|
|
instance_variable_get(ivar(name))
|
2017-11-13 10:27:30 -05:00
|
|
|
else
|
2017-12-11 10:38:16 -05:00
|
|
|
instance_variable_set(ivar(name), yield)
|
2017-11-13 10:27:30 -05:00
|
|
|
end
|
|
|
|
end
|
2017-12-11 10:38:16 -05:00
|
|
|
|
2019-09-04 04:14:24 -04:00
|
|
|
def strong_memoized?(name)
|
|
|
|
instance_variable_defined?(ivar(name))
|
|
|
|
end
|
|
|
|
|
2017-12-11 10:38:16 -05:00
|
|
|
def clear_memoization(name)
|
|
|
|
remove_instance_variable(ivar(name)) if instance_variable_defined?(ivar(name))
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def ivar(name)
|
|
|
|
"@#{name}"
|
|
|
|
end
|
2017-11-13 10:27:30 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|