Class: Gitlab::Graphql::Loaders::LazyRelationLoader::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb

Constant Summary collapse

PrematureQueryExecutionTriggered =
Class.new(RuntimeError)
PROHIBITED_METHODS =

Following methods are Active Record kicker methods which fire SQL query. We can support some of them with TopNLoader but for now restricting their use as we don’t have a use case.

(
  ActiveRecord::FinderMethods.instance_methods(false) +
  ActiveRecord::Calculations.instance_methods(false)
).to_set.freeze

Instance Method Summary collapse

Constructor Details

#initialize(relation) ⇒ Registry

Returns a new instance of Registry.



17
18
19
20
21
22
# File 'lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb', line 17

def initialize(relation)
  @parents = []
  @relation = relation
  @records = []
  @loaded = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb', line 28

def method_missing(method_name, ...)
  raise PrematureQueryExecutionTriggered if PROHIBITED_METHODS.include?(method_name)

  result = relation.public_send(method_name, ...) # rubocop:disable GitlabSecurity/PublicSend

  if result.is_a?(ActiveRecord::Relation) # Spawn methods generate a new relation (e.g. where, limit)
    @relation = result

    return self
  end

  result
end

Instance Method Details

#for(object) ⇒ Object



53
54
55
56
# File 'lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb', line 53

def for(object)
  load.select { |record| record[foreign_key] == object[active_record_primary_key] }
      .tap { |records| set_inverse_of(object, records) }
end

#loadObject



46
47
48
49
50
51
# File 'lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb', line 46

def load
  return records if loaded

  @loaded = true
  @records = TopNLoader.load(relation, parents)
end

#register(object) ⇒ Object



24
25
26
# File 'lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb', line 24

def register(object)
  @parents << object
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/gitlab/graphql/loaders/lazy_relation_loader/registry.rb', line 42

def respond_to_missing?(method_name, include_private = false)
  relation.respond_to?(method_name, include_private)
end