Class: GraphqlLazyLoad::ActiveRecordRelation

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql_lazy_load.rb

Instance Method Summary collapse

Constructor Details

#initialize(type, association, scope: nil) ⇒ ActiveRecordRelation

Returns a new instance of ActiveRecordRelation.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/graphql_lazy_load.rb', line 74

def initialize(type, association, scope: nil)
  @object_class = type.object.class
  @object_id = type.object.id
  @association = association
  @scope = scope
  # Initialize the loading state for this query,
  # or get the previously-initiated state
  # scope cant be used as a hash key because when .hash is called on diff
  # for ~same~ scopes its diff every time but scope == scope will return true if ~same~
  @lazy = (type.context[context_key] ||= []).find { |c| c[:scope] == scope }
  unless @lazy
    @lazy = {
      objects_to_load: Set.new,
      ids: Set.new,
      results: {}
    }
    type.context[context_key].push(@lazy)
  end
  # Register this to be loaded later unless we've already queued or loaded it
  return if already_loaded_or_queued?
  # use copy of object so it doesnt add preload to associations.
  # this is so associations dont get loaded to object passed so different scopes get reloaded
  lazy_objects.add(object_class.new(type.object.attributes))
  lazy_ids.add(object_id)
end

Instance Method Details

#resultObject

Return the loaded record, hitting the database if needed



101
102
103
104
105
106
107
108
109
110
# File 'lib/graphql_lazy_load.rb', line 101

def result
  if !already_loaded? && any_to_load?
    ActiveRecord::Associations::Preloader.new.preload(lazy_objects.to_a, association, scope)
    lazy_objects.each do |object|
      lazy_results[object.id] = object.send(association)
    end
    lazy_objects.clear
  end
  lazy_results[object_id]
end