debian-mirror-gitlab/lib/gitlab/utils/strong_memoize.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

60 lines
1.4 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2018-03-17 18:26:18 +05:30
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:
#
# include Gitlab::Utils::StrongMemoize
#
# def trigger_from_token
# strong_memoize(:trigger) do
# Ci::Trigger.find_by_token(params[:token].to_s)
# end
# end
#
def strong_memoize(name)
2022-05-07 20:08:51 +05:30
key = ivar(name)
if instance_variable_defined?(key)
instance_variable_get(key)
2018-03-17 18:26:18 +05:30
else
2022-05-07 20:08:51 +05:30
instance_variable_set(key, yield)
2018-03-17 18:26:18 +05:30
end
end
2019-12-04 20:38:33 +05:30
def strong_memoized?(name)
instance_variable_defined?(ivar(name))
end
2018-03-17 18:26:18 +05:30
def clear_memoization(name)
2022-05-07 20:08:51 +05:30
key = ivar(name)
remove_instance_variable(key) if instance_variable_defined?(key)
2018-03-17 18:26:18 +05:30
end
private
2022-05-07 20:08:51 +05:30
# Convert `"name"`/`:name` into `:@name`
#
# Depending on a type ensure that there's a single memory allocation
2018-03-17 18:26:18 +05:30
def ivar(name)
2022-05-07 20:08:51 +05:30
if name.is_a?(Symbol)
name.to_s.prepend("@").to_sym
elsif name.is_a?(String)
:"@#{name}"
else
raise ArgumentError, "Invalid type of '#{name}'"
end
2018-03-17 18:26:18 +05:30
end
end
end
end