Module: Gitlab::Utils::StrongMemoize

Included in:
API::APIGuard, API::ComposerPackages, API::Helpers::Runner, API::Terraform::State, AlertManagement::Alert, AlertManagement::AlertPresenter, AlertManagement::Alerts::UpdateService, AlertManagement::CreateAlertIssueService, AlertManagement::ProcessPrometheusAlertService, Analytics::CycleAnalytics::Stage, AppearancesHelper, ApplicationController, ApplicationSetting::TermPolicy, ApplicationSettingImplementation, AuthorizedProjectUpdate::ProjectGroupLinkCreateService, AutoMerge::BaseService, AutoMergeService, Autocomplete::UsersFinder, AwardEmojis::AddService, Banzai::Filter::BaseRelativeLinkFilter, Banzai::Filter::BaseSanitizationFilter, Banzai::Filter::InlineMetricsRedactorFilter, Banzai::Filter::MilestoneReferenceFilter, Banzai::ReferenceParser::ProjectParser, BlobViewer::GoMod, BlobViewer::MetricsDashboardYml, Blobs::UnfoldPresenter, Boards::Issues::ListService, Boards::Lists::CreateService, BoardsActions, BoardsResponses, Ci::BuildMetadata, Ci::BuildRunnerPresenter, Ci::CreateDownstreamPipelineService, Ci::CreateWebIdeTerminalService, Ci::Group, Ci::Pipeline, Ci::PipelineArtifacts::CodeCoveragePresenter, Ci::PipelinePresenter, Ci::PipelineProcessing::AtomicProcessingService, Ci::PipelineProcessing::AtomicProcessingService::StatusCollection, Ci::PipelineTriggerService, Ci::PipelinesForMergeRequestFinder, Ci::Processable, Ci::WebIdeConfigService, ClusterAncestorsFinder, Clusters::Applications::CheckIngressIpAddressService, Clusters::Applications::ElasticStack, Clusters::Applications::Helm, Clusters::Applications::PrometheusHealthCheckService, Clusters::Aws::FinalizeCreationService, Clusters::Cluster, Clusters::ClusterPresenter, Clusters::KnativeServicesFinder, Clusters::ParseClusterApplicationsArtifactService, Clusters::Providers::Aws, Commit, CommitCollection, Compare, ContainerExpirationPolicies::UpdateService, ContainerRegistry::Client, ContainerRegistry::Tag, ContainerRepository, CreatesCommit, DeployToken, Deployment, DeploymentMetrics, DesignManagement::Design, DesignManagement::DesignAtVersion, DesignManagement::Version, DiffFileBaseEntity, DiffNote, Discussions::ResolveService, DraftNote, EachShardWorker, Environment, EnvironmentStatus, ErrorTracking::IssueDetailsService, ErrorTracking::ProjectErrorTrackingSetting, ErrorTrackingIssueLinkWorker, Event, EventCollection, EventFilter, ExternalPullRequest, FileMover, FindSnippet, Flowdock::Git::Builder, Git::BaseHooksService, Git::BranchPushService, Git::WikiPushService::Change, AlertManagement::AlertStatusCounts, AlertManagement::Payload::Base, Alerting::Alert, Analytics::CycleAnalytics::DataCollector, Analytics::CycleAnalytics::RecordsFetcher, Auth::Activity, Auth::Atlassian::IdentityLinker, Auth::AuthFinders, Auth::IpRateLimiter, Auth::KeyStatusChecker, BackgroundMigration::LegacyUploadMover, BackgroundMigration::MergeRequestAssigneesMigrationProgressCheck, BareRepositoryImport::Repository, BlobHelper, Cache::Ci::ProjectPipelineStatus, Chat::Command, Checks::BaseChecker, Checks::DiffCheck, Ci::Build::AutoRetry, Ci::Build::Context::Build, Ci::Build::Context::Global, Ci::Build::Prerequisite::Base, Ci::Build::Rules, Ci::Config::Entry::Product::Matrix, Ci::Config::Entry::Root, Ci::Config::Extendable::Entry, 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::EvaluateWorkflowRules, Ci::Pipeline::Chain::Seed, Ci::Pipeline::Chain::Skip, Ci::Pipeline::Expression::Lexer, Ci::Pipeline::Metrics, Ci::Pipeline::Seed::Build, Ci::Pipeline::Seed::Build::ResourceGroup, Ci::Pipeline::Seed::Stage, Ci::Reports::AccessibilityReportsComparer, Ci::Reports::TestReportsComparer, Ci::Reports::TestSuiteComparer, Ci::Status::Composite, Ci::Trace::Metrics, Cleanup::OrphanJobArtifactFiles, Cleanup::OrphanJobArtifactFilesBatch, Cleanup::OrphanLfsFileReferences, CodeNavigationPath, Config::Loader::Yaml, Conflict::File, CycleAnalytics::UsageData, Diff::File, Diff::FileCollection::Base, Diff::HighlightCache, Diff::LinesUnfolder, Diff::StatsCache, Diff::Suggestion, Diff::SuggestionDiff, DiscussionsDiff::FileCollection, Email::Handler::ServiceDeskHandler, Email::Hook::DeliveryMetricsObserver, ExternalAuthorization::Response, Git::Commit, Git::DiffStatsCollection, Git::MergeBase, Git::Push, Git::Repository, GitAccess, GithubImport::Client, GithubImport::Importer::RepositoryImporter, GlRepository::Identifier, Graphql::Pagination::Keyset::Connection, HealthChecks::UnicornCheck, I18n::PoLinter, ImportExport::Base::RelationFactory, ImportExport::DecompressedArchiveSizeValidator, ImportExport::FastHashSerializer::JSONBatchRelation, ImportExport::Group::LegacyTreeRestorer, ImportExport::Group::TreeRestorer, ImportExport::Importer, ImportExport::JSON::LegacyReader::File, ImportExport::LfsRestorer, ImportExport::Project::TreeRestorer, Instrumentation::RedisBase, Instrumentation::RedisPayload, IssuableMetadata, JwtAuthenticatable::ClassMethods, Kubernetes::KubeClient, LanguageData, LetsEncrypt::Client, Metrics::Dashboard::ServiceSelector, Metrics::Dashboard::Stages::AlertsInserter, Metrics::Dashboard::Stages::GrafanaFormatter, Metrics::Dashboard::Url, PrometheusClient, RepositoryCacheAdapter, RequestContext, Search::FoundBlob, Search::ParsedQuery, Serverless::Service, SidekiqDaemon::MemoryKiller, SidekiqDaemon::Monitor, SidekiqQueue, SignedCommit, SubmoduleLinks, Suggestions::FileSuggestion, TaskHelpers, Template::GitlabCiYmlTemplate, TreeSummary, Gitlab::UsageData, LazyAttributes, WikiPages::FrontMatterParser::Block, X509::Signature, X509::Tag, GoogleApi::AuthorizationsController, Grafana::TimeWindow, Group, HasRepository, Impersonation, ImportHelper, IncidentManagement::PagerDuty::ProcessWebhookService, IncidentManagement::ProjectIncidentManagementSetting, IncidentManagement::Settings, Integrations::Test::ProjectService, InternalId, InvitesController, IssuableActions, IssuableCollections, IssuableFinder, IssuableFinder::Params, Issues::ResolveDiscussions, JiraConnect::ApplicationController, JiraConnectSubscriptions::CreateService, JiraService, KnownSignIn, LabelsFinder, LicenseTemplateFinder, LinkedProjectIssueEntity, Member, Mentionable::ReferenceRegexes, MergeRequest, MergeRequestDiff, MergeRequestPresenter, MergeRequests::BuildService, MergeRequests::MergeBaseService, MergeRequests::MergeabilityCheckService, MergeRequests::PushedBranchesService, MergeRequests::RefreshService, MergeRequestsHelper, Metrics::Dashboard::CloneDashboardService, Metrics::Dashboard::CustomMetricEmbedService, Metrics::Dashboard::DynamicEmbedService, Metrics::Dashboard::GitlabAlertEmbedService, MultipleBoardsActions, Namespace, Note, NotePolicy, NotesActions, NotificationRecipient, ObjectStorage::DirectUpload, Operations::FeatureFlagScope, OperationsHelper, Packages::Composer::CreatePackageService, Packages::Conan::PackagePresenter, Packages::Go::Module, Packages::Go::ModuleVersion, 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::Pypi::CreatePackageService, Packages::UpdateTagsService, PipelineEntity, ProductAnalytics::Tracker, Project, ProjectPresenter, Projects::Alerting::NotifyService, Projects::Ci::DailyBuildGroupReportResultsController, Projects::CleanupService, Projects::ContainerRepository::Gitlab::DeleteTagsService, Projects::CreateFromTemplateService, Projects::ForksController, Projects::GitlabProjectsImportService, Projects::LfsPointers::LfsObjectDownloadListService, Projects::LogsController, Projects::MergeRequests::DraftsController, Projects::MetricsDashboardController, Projects::MilestonesController, Projects::OpenIssuesCountService, Projects::Pipelines::ApplicationController, Projects::PipelinesController, Projects::Prometheus::Alerts::NotifyService, Projects::Prometheus::Metrics::BaseService, Projects::Serverless::FunctionsFinder, Projects::Settings::DeployKeysPresenter, Projects::TodosController, Projects::UpdatePagesConfigurationService, Prometheus::CleanupMultiprocDirService, Prometheus::CreateDefaultAlertsService, Prometheus::ProxyService, QuickActions::InterpretService, RedisCacheable, Release, Releases::Concerns, ReleasesFinder, Repositories::GitHttpClientController, Repositories::LfsApiController, ResolvableDiscussion, Resolvers::BaseResolver, ResourceAccessTokens::RevokeService, ResourceEvent, ResourceEvents::BaseSyntheticNotesBuilderService, ResourceEvents::MergeIntoNotesService, SafeZip::ExtractParams, Search::GlobalService, ServiceDeskSetting, SessionsController, SnippetInputActionCollection, Snippets::BlobsActions, SnippetsFinder, SpammableActions, StateNote, Submodules::UpdateService, Suggestible, SuggestionEntity, TemplateFinder, TestHooks::ProjectService, TestHooks::SystemService, TimeboxesHelper, TodosFinder, Tree, Types::BoardListType, Uploads::Fog, UploadsActions, Wiki, WikiActions, WikiPage, WikiPage::Meta
Defined in:
lib/gitlab/utils/strong_memoize.rb

Instance Method Summary collapse

Instance Method Details

#clear_memoization(name) ⇒ Object


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

def clear_memoization(name)
  remove_instance_variable(ivar(name)) if instance_variable_defined?(ivar(name))
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

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

def strong_memoize(name)
  if strong_memoized?(name)
    instance_variable_get(ivar(name))
  else
    instance_variable_set(ivar(name), 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