strong_memoize.rb 1.05 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
require_dependency 'gitlab/utils'

5 6 7 8 9 10 11 12 13 14 15 16 17
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:
      #
18 19
      #     include Gitlab::Utils::StrongMemoize
      #
20 21 22 23 24 25 26
      #     def trigger_from_token
      #       strong_memoize(:trigger) do
      #         Ci::Trigger.find_by_token(params[:token].to_s)
      #       end
      #     end
      #
      def strong_memoize(name)
27 28
        if instance_variable_defined?(ivar(name))
          instance_variable_get(ivar(name))
29
        else
30
          instance_variable_set(ivar(name), yield)
31 32
        end
      end
33 34 35 36 37 38 39 40 41 42

      def clear_memoization(name)
        remove_instance_variable(ivar(name)) if instance_variable_defined?(ivar(name))
      end

      private

      def ivar(name)
        "@#{name}"
      end
43 44 45
    end
  end
end