Class: Graphiform::AssociationSource

Inherits:
GraphQL::Dataloader::Source
  • Object
show all
Defined in:
lib/graphiform/association_source.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, attribute, **options) ⇒ AssociationSource

Returns a new instance of AssociationSource.



5
6
7
8
9
10
11
# File 'lib/graphiform/association_source.rb', line 5

def initialize(model, attribute, **options)
  super()

  @model = model
  @attribute = attribute
  @options = options
end

Instance Method Details

#fetch(values) ⇒ Object



13
14
15
16
17
# File 'lib/graphiform/association_source.rb', line 13

def fetch(values)
  normalized_values = normalize_values(values)
  records = query(normalized_values.uniq).to_a
  results(normalized_values, records)
end

#normalize_value(value) ⇒ Object



31
32
33
34
35
# File 'lib/graphiform/association_source.rb', line 31

def normalize_value(value)
  value = value.downcase if !@options[:case_sensitive] && value.is_a?(String)

  value
end

#normalize_values(values) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/graphiform/association_source.rb', line 37

def normalize_values(values)
  type_for_attribute = @model.type_for_attribute(@attribute) if @model.respond_to?(:type_for_attribute)
  values.map do |value|
    value = type_for_attribute.cast(value) if type_for_attribute.present?
    normalize_value(value)
  end
end

#query(values) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/graphiform/association_source.rb', line 19

def query(values)
  query = @model
  query = query.merge(@model.instance_exec(&@options[:scope])) if @options[:scope].present?
  query = query.where(@attribute => values)

  query = query.includes(@options[:includes]) if @options[:includes].present? && query.respond_to?(:includes)
  query = query.apply_filters(@options[:where].to_h) if @options[:where].present? && query.respond_to?(:apply_filters)
  query = query.apply_sorts(@options[:sort].to_h) if @options[:sort].present? && query.respond_to?(:apply_sorts)

  query
end

#results(values, records) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/graphiform/association_source.rb', line 45

def results(values, records)
  record_attributes = records.map { |record| normalize_value(record[@attribute]) }
  values.map do |value|
    if @options[:multi]
      indexes = record_attributes.each_index.select { |index| record_attributes[index] == value }
      indexes.map { |index| index && records[index] }
    else
      index = record_attributes.index(value)
      index && records[index]
    end
  end
end