debian-mirror-gitlab/lib/gitlab/issuables_count_for_state.rb

60 lines
1.4 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2018-03-17 18:26:18 +05:30
module Gitlab
# Class for counting and caching the number of issuables per state.
class IssuablesCountForState
2018-12-05 23:21:45 +05:30
# The name of the Gitlab::SafeRequestStore cache key.
2018-03-17 18:26:18 +05:30
CACHE_KEY = :issuables_count_for_state
# The state values that can be safely casted to a Symbol.
STATES = %w[opened closed merged all].freeze
2020-10-24 23:57:45 +05:30
attr_reader :project
def self.declarative_policy_class
'IssuablePolicy'
end
2018-03-17 18:26:18 +05:30
# finder - The finder class to use for retrieving the issuables.
2020-10-24 23:57:45 +05:30
def initialize(finder, project = nil)
2018-03-17 18:26:18 +05:30
@finder = finder
2020-10-24 23:57:45 +05:30
@project = project
2018-12-05 23:21:45 +05:30
@cache = Gitlab::SafeRequestStore[CACHE_KEY] ||= initialize_cache
2018-03-17 18:26:18 +05:30
end
def for_state_or_opened(state = nil)
self[state || :opened]
end
2020-10-24 23:57:45 +05:30
# Define method for each state
STATES.each do |state|
define_method(state) { self[state] }
end
2018-03-17 18:26:18 +05:30
# Returns the count for the given state.
#
# state - The name of the state as either a String or a Symbol.
#
# Returns an Integer.
def [](state)
state = state.to_sym if cast_state_to_symbol?(state)
cache_for_finder[state] || 0
end
private
def cache_for_finder
@cache[@finder]
end
def cast_state_to_symbol?(state)
state.is_a?(String) && STATES.include?(state)
end
def initialize_cache
Hash.new { |hash, finder| hash[finder] = finder.count_by_state }
end
end
end