Class: Gitlab::ApplicationContext

Inherits:
Object
  • Object
show all
Includes:
Utils::LazyAttributes
Defined in:
lib/gitlab/application_context.rb

Overview

A GitLab-rails specific accessor for `Labkit::Logging::ApplicationContext`

Defined Under Namespace

Classes: Attribute

Constant Summary collapse

APPLICATION_ATTRIBUTES =
[
  Attribute.new(:project, Project),
  Attribute.new(:namespace, Namespace),
  Attribute.new(:user, User),
  Attribute.new(:caller_id, String),
  Attribute.new(:related_class, String),
  Attribute.new(:feature_category, String)
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::StrongMemoize

#clear_memoization, #strong_memoize, #strong_memoized?

Constructor Details

#initialize(**args) ⇒ ApplicationContext

Returns a new instance of ApplicationContext.

Raises:

  • (ArgumentError)

33
34
35
36
37
38
39
40
# File 'lib/gitlab/application_context.rb', line 33

def initialize(**args)
  unknown_attributes = args.keys - APPLICATION_ATTRIBUTES.map(&:name)
  raise ArgumentError, "#{unknown_attributes} are not known keys" if unknown_attributes.any?

  @set_values = args.keys

  assign_attributes(args)
end

Class Method Details

.current_context_include?(attribute_name) ⇒ Boolean

Returns:

  • (Boolean)

29
30
31
# File 'lib/gitlab/application_context.rb', line 29

def self.current_context_include?(attribute_name)
  Labkit::Context.current.to_h.include?(Labkit::Context.log_key(attribute_name))
end

.push(args) ⇒ Object


24
25
26
27
# File 'lib/gitlab/application_context.rb', line 24

def self.push(args)
  application_context = new(**args)
  Labkit::Context.push(application_context.to_lazy_hash)
end

.with_context(args, &block) ⇒ Object


19
20
21
22
# File 'lib/gitlab/application_context.rb', line 19

def self.with_context(args, &block)
  application_context = new(**args)
  application_context.use(&block)
end

Instance Method Details

#to_lazy_hashObject


42
43
44
45
46
47
48
49
50
51
# File 'lib/gitlab/application_context.rb', line 42

def to_lazy_hash
  {}.tap do |hash|
    hash[:user] = -> { username } if set_values.include?(:user)
    hash[:project] = -> { project_path } if set_values.include?(:project)
    hash[:root_namespace] = -> { root_namespace_path } if include_namespace?
    hash[:caller_id] = caller_id if set_values.include?(:caller_id)
    hash[:related_class] = related_class if set_values.include?(:related_class)
    hash[:feature_category] = feature_category if set_values.include?(:feature_category)
  end
end

#useObject


53
54
55
# File 'lib/gitlab/application_context.rb', line 53

def use
  Labkit::Context.with_context(to_lazy_hash) { yield }
end