Class: GraphqlLazyLoad::ActiveRecordRelation
- Inherits:
-
Object
- Object
- GraphqlLazyLoad::ActiveRecordRelation
- Defined in:
- lib/graphql_lazy_load.rb
Instance Method Summary collapse
-
#initialize(type, association, scope: nil) ⇒ ActiveRecordRelation
constructor
A new instance of ActiveRecordRelation.
-
#result ⇒ Object
Return the loaded record, hitting the database if needed.
Constructor Details
#initialize(type, association, scope: nil) ⇒ ActiveRecordRelation
Returns a new instance of ActiveRecordRelation.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/graphql_lazy_load.rb', line 8 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: {}, scope: scope } 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
#result ⇒ Object
Return the loaded record, hitting the database if needed
36 37 38 39 40 41 42 43 44 45 |
# File 'lib/graphql_lazy_load.rb', line 36 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 |