Class: GraphQL::Dataloader::ActiveRecordSource
- Defined in:
- lib/graphql/dataloader/active_record_source.rb
Constant Summary
Constants inherited from Source
Instance Attribute Summary
Attributes inherited from Source
#dataloader, #pending, #results
Instance Method Summary collapse
-
#fetch(record_ids) ⇒ Object
-
#initialize(model_class, find_by: model_class.primary_key) ⇒ ActiveRecordSource
constructor
A new instance of ActiveRecordSource.
-
#normalize_fetch_key(requested_key) ⇒ Object
-
#result_key_for(requested_key) ⇒ Object
Methods inherited from Source
batch_key_for, #clear_cache, #load, #load_all, #merge, #pending?, #request, #request_all, #run_pending_keys, #setup, #sync
Constructor Details
#initialize(model_class, find_by: model_class.primary_key) ⇒ ActiveRecordSource
Returns a new instance of ActiveRecordSource.
7 8 9 10 11 12 13 14 15 16 |
# File 'lib/graphql/dataloader/active_record_source.rb', line 7 def initialize(model_class, find_by: model_class.primary_key) @model_class = model_class @find_by = find_by @find_by_many = find_by.is_a?(Array) if @find_by_many @type_for_column = @find_by.map { |fb| @model_class.type_for_attribute(fb) } else @type_for_column = @model_class.type_for_attribute(@find_by) end end |
Instance Method Details
#fetch(record_ids) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/graphql/dataloader/active_record_source.rb', line 32 def fetch(record_ids) records = @model_class.where(@find_by => record_ids) record_lookup = {} if @find_by_many records.each do |r| key = @find_by.map { |fb| r.public_send(fb) } record_lookup[key] = r end else records.each { |r| record_lookup[r.public_send(@find_by)] = r } end record_ids.map { |id| record_lookup[id] } end |
#normalize_fetch_key(requested_key) ⇒ Object
22 23 24 25 26 27 28 29 30 |
# File 'lib/graphql/dataloader/active_record_source.rb', line 22 def normalize_fetch_key(requested_key) if @find_by_many requested_key.each_with_index.map do |k, idx| @type_for_column[idx].cast(k) end else @type_for_column.cast(requested_key) end end |
#result_key_for(requested_key) ⇒ Object
18 19 20 |
# File 'lib/graphql/dataloader/active_record_source.rb', line 18 def result_key_for(requested_key) normalize_fetch_key(requested_key) end |