Module: Gitlab::Utils::StrongMemoize

Included in:
API::APIGuard, API::Ci::Helpers::Runner, API::ComposerPackages, API::ContainerRepositories, API::Entities::BasicProjectDetails, API::Helpers::Packages::BasicAuthHelpers, API::Helpers::Packages::Conan::ApiHelpers, API::Helpers::Packages::Npm, API::Terraform::State, AlertManagement::Alert, AlertManagement::AlertProcessing, AlertManagement::Alerts::UpdateService, AlertManagement::CreateAlertIssueService, Analytics::CycleAnalytics::Stage, Analytics::CycleAnalytics::StageActions, AppearancesHelper, ApplicationController, ApplicationSetting::TermPolicy, ApplicationSettingImplementation, Atlassian::JiraConnect::Jwt::Asymmetric, Atlassian::JiraConnect::Jwt::Symmetric, Auth::DependencyProxyAuthenticationService, AuthorizedProjectUpdate::ProjectRecalculateService, AutoMerge::BaseService, AutoMergeService, Autocomplete::UsersFinder, AwardEmojis::AddService, Banzai::Filter::BaseRelativeLinkFilter, Banzai::Filter::BaseSanitizationFilter, Banzai::Filter::CustomEmojiFilter, Banzai::Filter::InlineMetricsRedactorFilter, Banzai::Filter::IssuableReferenceExpansionFilter, Banzai::Filter::References::ReferenceCache, Banzai::ReferenceParser::MergeRequestParser, Banzai::ReferenceParser::ProjectParser, BaseProjectService, BlobViewer::GoMod, BlobViewer::MetricsDashboardYml, Blobs::UnfoldPresenter, Boards::BaseItemsListService, Boards::Issues::ListService, Boards::Lists::BaseCreateService, BoardsActions, BoardsResponses, BroadcastMessagesHelper, BulkImports::Clients::HTTP, BulkImports::Export, BulkImports::ExportStatus, BulkImports::FileTransfer::BaseConfig, BulkImports::Pipeline, BulkImports::UsersMapper, CascadingNamespaceSettingAttribute, Ci::BuildDependencies, Ci::BuildMetadata, Ci::BuildRunnerPresenter, Ci::CommitStatusesFinder, Ci::CreateDownstreamPipelineService, Ci::CreateWebIdeTerminalService, Ci::Group, Ci::JobArtifact, Ci::JobArtifacts::DestroyBatchService, Ci::ParseDotenvArtifactService, Ci::Pipeline, Ci::PipelineArtifacts::CodeCoveragePresenter, Ci::PipelineArtifacts::CodeQualityMrDiffPresenter, Ci::PipelineArtifacts::CoverageReportService, Ci::PipelineArtifacts::CreateCodeQualityMrDiffReportService, Ci::PipelineArtifacts::DestroyAllExpiredService, Ci::PipelineEntity, Ci::PipelinePresenter, Ci::PipelineProcessing::AtomicProcessingService, Ci::PipelineProcessing::AtomicProcessingService::StatusCollection, Ci::PipelineSchedules::CalculateNextRunService, Ci::PipelineTriggerService, Ci::Pipelines::HookService, Ci::PipelinesForMergeRequestFinder, Ci::Processable, Ci::Queue::BuildQueueService, Ci::RetryJobService, Ci::Runner, Ci::UpdateBuildStateService, ClusterAncestorsFinder, Clusters::Agents::RefreshAuthorizationService, Clusters::Applications::CheckIngressIpAddressService, Clusters::Applications::Helm, Clusters::Aws::FinalizeCreationService, Clusters::Cluster, Clusters::ClusterPresenter, Clusters::Integrations::PrometheusHealthCheckService, Clusters::KnativeServicesFinder, Clusters::Providers::Aws, Commit, CommitCollection, Compare, ContainerExpirationPolicies::CleanupContainerRepositoryWorker, ContainerExpirationPolicies::UpdateService, ContainerRegistry::Client, ContainerRegistry::Event, ContainerRegistry::GitlabApiClient, ContainerRegistry::Migration::EnqueuerWorker, ContainerRegistry::Tag, ContainerRepository, CreatesCommit, Crm::ContactsFinder, Crm::OrganizationsFinder, Database::BatchedBackgroundMigration::SingleDatabaseWorker, DependencyProxy::CleanupBlobWorker, DependencyProxy::CleanupManifestWorker, DependencyProxy::ImageTtlGroupPolicies::UpdateService, DeployToken, Deployment, DeploymentMetrics, DesignManagement::Design, DesignManagement::DesignAtVersion, DesignManagement::Version, DiffFileBaseEntity, DiffFileConflictType, DiffFileEntity, DiffNote, Discussions::ResolveService, Discussions::UnresolveService, DraftNote, EachShardWorker, Environment, EnvironmentStatus, ErrorTracking::CollectErrorService, ErrorTracking::IssueDetailsService, ErrorTracking::ProjectErrorTrackingSetting, ErrorTrackingIssueLinkWorker, Event, EventCollection, EventFilter, ExternalPullRequest, FeatureFlags::BaseService, FileMover, FindSnippet, Flowdock::Git::Builder, Git::BaseHooksService, Git::BranchPushService, Git::WikiPushService::Change, AlertManagement::AlertStatusCounts, AlertManagement::Payload::Base, Analytics::CycleAnalytics::Aggregated::DataCollector, Analytics::CycleAnalytics::Aggregated::RecordsFetcher, Analytics::CycleAnalytics::Average, Analytics::CycleAnalytics::DataCollector, Analytics::CycleAnalytics::RecordsFetcher, Analytics::CycleAnalytics::RequestParams, ApplicationContext, Auth::Activity, Auth::Atlassian::IdentityLinker, Auth::AuthFinders, Auth::IpRateLimiter, Auth::KeyStatusChecker, Auth::Otp::Strategies::FortiTokenCloud, BackgroundMigration::LegacyUploadMover, BareRepositoryImport::Repository, BlobHelper, Cache::Ci::ProjectPipelineStatus, Chat::Command, Checks::BaseChecker, Checks::ChangesAccess, Checks::DiffCheck, Ci::Artifacts::Metrics, Ci::Build::AutoRetry, Ci::Build::Cache, Ci::Build::Context::Base, Ci::Build::Context::Build, Ci::Build::Context::Global, Ci::Build::Prerequisite::Base, Ci::Build::Rules, Ci::Build::Rules::Rule::Clause::Changes, Ci::Config, Ci::Config::Entry::Product::Matrix, Ci::Config::Entry::Root, Ci::Config::Extendable::Entry, Ci::Config::External::Context, Ci::Config::External::File::Artifact, Ci::Config::External::File::Base, Ci::Config::External::File::Local, Ci::Config::External::File::Project, Ci::Config::External::File::Remote, Ci::Config::External::Mapper, Ci::Config::Normalizer, Ci::Config::Normalizer::Factory, Ci::Pipeline::Chain::Command, Ci::Pipeline::Chain::Config::Content::Source, Ci::Pipeline::Chain::Create, Ci::Pipeline::Chain::EvaluateWorkflowRules, Ci::Pipeline::Chain::Limit::RateLimit, Ci::Pipeline::Chain::Seed, Ci::Pipeline::Chain::SeedBlock, Ci::Pipeline::Chain::Skip, Ci::Pipeline::Expression::Lexer, Ci::Pipeline::Logger, Ci::Pipeline::Metrics, Ci::Pipeline::Quota::Deployments, Ci::Pipeline::Seed::Build, Ci::Pipeline::Seed::Pipeline, Ci::Pipeline::Seed::Processable::ResourceGroup, Ci::Pipeline::Seed::Stage, Ci::Queue::Metrics, Ci::Reports::CoverageReportGenerator, Ci::Reports::ReportsComparer, Ci::Reports::Security::FindingMatcher, Ci::Reports::Security::Locations::Base, Ci::Reports::Security::ScannedResource, Ci::Reports::Security::VulnerabilityReportsComparer, Ci::Reports::TestFailureHistory, Ci::Reports::TestReportsComparer, Ci::Reports::TestSuiteComparer, Ci::Reports::TestSuiteSummary, Ci::Runner::Metrics, Ci::Status::Composite, Ci::Tags::BulkInsert, Ci::Trace, Ci::Trace::Archive, Ci::Trace::Backoff, Ci::Trace::Checksum, Ci::Trace::Metrics, Ci::Trace::RemoteChecksum, Ci::Variables::Builder, Ci::Variables::Builder::Group, Ci::Variables::Builder::Instance, Ci::Variables::Builder::Project, Ci::Variables::Collection::Item, Ci::Variables::Collection::Sort, Cleanup::OrphanJobArtifactFiles, Cleanup::OrphanJobArtifactFilesBatch, Cleanup::OrphanLfsFileReferences, CodeNavigationPath, Config::Entry::ComposableArray, Config::Loader::Yaml, Conflict::File, Database::AsWithMaterialized, Database::BackgroundMigration::PrometheusMetrics, Database::BulkUpdate::Setter, Database::LoadBalancing::SidekiqClientMiddleware, Database::LoadBalancing::SrvResolver, Database::Metrics, Database::PostgresIndex, Diff::CharDiff, Diff::File, Diff::FileCollection::Base, Diff::HighlightCache, Diff::LinesUnfolder, Diff::Rendered::Notebook::DiffFile, Diff::StatsCache, Diff::Suggestion, Diff::SuggestionDiff, DiscussionsDiff::FileCollection, Email::Handler::ServiceDeskHandler, Email::Hook::DeliveryMetricsObserver, Email::Message::InProductMarketing::Experience, Email::Receiver, ExternalAuthorization::Response, Gfm::ReferenceRewriter, Gfm::UploadsRewriter, Git::Commit, Git::DiffStatsCollection, Git::MergeBase, Git::Push, Git::Repository, Git::WikiPageVersion, GitAccess, GithubImport::Client, GithubImport::Importer::RepositoryImporter, GithubImport::Representation::DiffNote, GithubImport::Representation::DiffNotes::SuggestionFormatter, GlRepository::Identifier, Graphql::Lazy, Graphql::Pagination::Keyset::Connection, I18n::PoLinter, ImportExport::Base::RelationFactory, ImportExport::Base::RelationObjectSaver, ImportExport::DecompressedArchiveSizeValidator, ImportExport::FastHashSerializer::JSONBatchRelation, ImportExport::Group::LegacyTreeRestorer, ImportExport::Group::TreeRestorer, ImportExport::Importer, ImportExport::Json::LegacyReader::File, ImportExport::LfsRestorer, ImportExport::Project::Sample::DateCalculator, ImportExport::Project::TreeRestorer, InactiveProjectsDeletionWarningTracker, Instrumentation::RedisBase, Instrumentation::RedisPayload, IssuableMetadata, JwtAuthenticatable::ClassMethods, Kubernetes::Deployment, Kubernetes::Ingress, Kubernetes::KubeClient, Kubernetes::RolloutInstances, LanguageData, LetsEncrypt::Client, Metrics::Dashboard::ServiceSelector, Metrics::Dashboard::Stages::GrafanaFormatter, Metrics::Dashboard::Url, Metrics::Subscribers::ActionCable, Metrics::Subscribers::ActiveRecord, PrometheusClient, RackAttack::Request, Recaptcha, Redis::MultiStore, RelativePositioning::EndingAt, RelativePositioning::ItemContext, RelativePositioning::StartingFrom, RepositoryCacheAdapter, RequestContext, Search::FoundBlob, Search::ParsedQuery, Security::ScanConfiguration, Serverless::Service, SidekiqDaemon::MemoryKiller, SidekiqDaemon::Monitor, SidekiqMiddleware::DuplicateJobs::DuplicateJob, SidekiqMiddleware::DuplicateJobs::Strategies::DeduplicatesWhenScheduling, SidekiqQueue, SignedCommit, SignedTag, Ssh::Signature, SubmoduleLinks, Suggestions::FileSuggestion, TaskHelpers, Template::GitlabCiYmlTemplate, Tracking::Destinations::SnowplowMicro, TreeSummary, Gitlab::UsageData, LazyAttributes, UsageData, WebHooks::RateLimiter, WebIde::Config::Entry::Terminal, Webpack::GraphqlKnownOperations, Webpack::Manifest, WikiPages::FrontMatterParser::Block, X509::Certificate, X509::Signature, X509::Tag, GoogleApi::AuthorizationsController, Grafana::TimeWindow, Group, Groups::BoardsController, Groups::CountService, Groups::DependencyProxyForContainersController, Groups::GroupMembersController, HasRepository, HasWikiPageMetaAttributes, IdeController, Impersonation, Import::GithubService, Import::GitlabProjects::FileAcquisitionStrategies::RemoteFileS3, ImportHelper, IncidentManagement::IssuableEscalationStatuses::PrepareUpdateService, IncidentManagement::PagerDuty::ProcessWebhookService, IncidentManagement::ProjectIncidentManagementSetting, IncidentManagement::Settings, Integrations::FieldEntity, Integrations::Jira, Integrations::Test::ProjectService, InternalId, InviteMembersHelper, InvitesController, IssuableActions, IssuableCollections, IssuableFinder, IssuableFinder::Params, Issuables::LabelFilter, IssuablesDescriptionTemplatesHelper, Issues::ReorderService, Issues::ResolveDiscussions, JiraConnect::ApplicationController, JiraConnectSubscriptions::CreateService, JiraImport::UsersMapperService, KnownSignIn, LabelsFinder, LearnGitlab::Onboarding, Lfs::PushService, LfsRequest, LicenseTemplateFinder, LimitedCapacity::JobTracker, LimitedCapacity::Worker, LinkedProjectIssueEntity, MarkdownContentRewriterService, Member, Members::InvitationReminderEmailService, Mentionable::ReferenceRegexes, MergeRequest, MergeRequestCleanupRefsWorker, MergeRequestDiff, MergeRequestPresenter, MergeRequests::AfterCreateService, MergeRequests::BuildService, MergeRequests::MergeBaseService, MergeRequests::MergeService, MergeRequests::Mergeability::RunChecksService, MergeRequests::MergeabilityCheckService, MergeRequests::OutdatedDiscussionDiffLinesService, MergeRequests::PushedBranchesService, MergeRequests::RefreshService, MergeRequestsHelper, Metrics::Dashboard::CloneDashboardService, Metrics::Dashboard::CustomMetricEmbedService, Metrics::Dashboard::DynamicEmbedService, Metrics::Dashboard::GitlabAlertEmbedService, MultipleBoardsActions, Namespace, Namespaces::PackageSettings::UpdateService, Note, NotePolicy, NotesActions, NotificationRecipient, Oauth::AuthorizationsController, ObjectStorage::DirectUpload, OperationsHelper, Packages::CleanupArtifactWorker, Packages::CleanupPackageFileWorker, Packages::Composer::CreatePackageService, Packages::Conan::PackagePresenter, Packages::Debian::ExtractChangesMetadataService, Packages::Debian::ExtractMetadataService, Packages::Debian::FindOrCreatePackageService, Packages::Debian::GenerateDistributionKeyService, Packages::Debian::GenerateDistributionService, Packages::Debian::GenerateDistributionWorker, Packages::Debian::ProcessChangesService, Packages::Debian::ProcessChangesWorker, Packages::Debian::SignDistributionService, Packages::Go::Module, Packages::Go::ModuleVersion, Packages::Helm::ProcessFileService, Packages::Maven::Metadata::BaseCreateXmlService, Packages::Maven::Metadata::SyncService, Packages::Maven::Metadata::SyncWorker, Packages::Npm::CreatePackageService, Packages::Npm::CreateTagService, Packages::Nuget::MetadataExtractionService, Packages::Nuget::PackagesMetadataPresenter, Packages::Nuget::SearchResultsPresenter, Packages::Nuget::SearchService, Packages::Nuget::SyncMetadatumService, Packages::Nuget::UpdatePackageFromMetadataService, Packages::Package, Packages::Pypi::CreatePackageService, Packages::Rubygems::DependencyResolverService, Packages::Rubygems::ProcessGemService, Packages::TerraformModule::CreatePackageService, Packages::UpdateTagsService, PageLayoutHelper, Pages::LookupPath, Pages::ZipDirectoryService, Project, ProjectPresenter, Projects::CleanupService, Projects::ContainerRepository::CleanupTagsService, Projects::ContainerRepository::Gitlab::DeleteTagsService, Projects::CreateFromTemplateService, Projects::ForksController, Projects::GitlabProjectsImportService, Projects::InactiveProjectsDeletionCronWorker, Projects::IncidentsController, Projects::LfsPointers::LfsObjectDownloadListService, Projects::Members::EffectiveAccessLevelFinder, Projects::MergeRequests::DraftsController, Projects::MetricsDashboardController, Projects::MilestonesController, Projects::OpenIssuesCountService, Projects::Pipelines::ApplicationController, Projects::PipelinesController, Projects::Prometheus::Alerts::NotifyService, Projects::Prometheus::Metrics::BaseService, Projects::RecordTargetPlatformsService, Projects::Settings::DeployKeysPresenter, Projects::TodosController, Projects::UpdateRemoteMirrorService, Projects::UpdateStatisticsService, ProjectsHelper, Prometheus::ProxyService, QuickActions::InterpretService, RedisCacheable, Release, Releases::BaseService, Releases::EvidencePipelineFinder, ReleasesFinder, Repositories::GitHttpClientController, Repositories::LfsApiController, RequireEmailVerification, ResolvableDiscussion, Resolvers::BaseResolver, ResourceAccessTokens::RevokeService, ResourceEvent, ResourceEvents::BaseSyntheticNotesBuilderService, ResourceEvents::MergeIntoNotesService, SafeZip::ExtractParams, Search::GlobalService, Search::ProjectService, SearchService, Security::CiConfiguration::SastParserService, ServiceDeskSetting, SessionsController, SessionsHelper, Sidebars::Groups::Menus::IssuesMenu, Sidebars::Groups::Menus::MergeRequestsMenu, Sidebars::Projects::Menus::AnalyticsMenu, Sidebars::Projects::Menus::IssuesMenu, Sidebars::Projects::Menus::LearnGitlabMenu, Sidebars::Projects::Menus::SecurityComplianceMenu, SnippetInputActionCollection, Snippets::BlobsActions, SnippetsFinder, StateNote, Submodules::UpdateService, Suggestible, SuggestionEntity, TemplateFinder, TestHooks::ProjectService, TestHooks::SystemService, TimeboxesHelper, Timelogs::BaseService, TodosFinder, Tree, Types::BoardListType, UnnestedInFilters::Rewriter, UpdateRepositoryStorageMethods, Uploads::Fog, UploadsActions, WhatsNewController, Wiki, WikiActions, WikiPage, WorkItem
Defined in:
lib/gitlab/utils/strong_memoize.rb

Instance Method Summary collapse

Instance Method Details

#clear_memoization(name) ⇒ Object


38
39
40
41
# File 'lib/gitlab/utils/strong_memoize.rb', line 38

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

#strong_memoize(name) ⇒ Object

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

24
25
26
27
28
29
30
31
32
# File 'lib/gitlab/utils/strong_memoize.rb', line 24

def strong_memoize(name)
  key = ivar(name)

  if instance_variable_defined?(key)
    instance_variable_get(key)
  else
    instance_variable_set(key, yield)
  end
end

#strong_memoized?(name) ⇒ Boolean

Returns:

  • (Boolean)

34
35
36
# File 'lib/gitlab/utils/strong_memoize.rb', line 34

def strong_memoized?(name)
  instance_variable_defined?(ivar(name))
end