Class: QueryHelper::Associations

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

Class Method Summary collapse

Class Method Details

.json_associations(associations) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/query_helper/associations.rb', line 31

def self.json_associations(associations)
  associations ||= []
  associations = associations.is_a?(Array) ? associations : [associations]
  associations.inject([]) do |translated, association|
    if association.is_a?(Symbol) || association.is_a?(String)
      translated << association.to_sym
    elsif association.is_a?(Array)
      translated << association.map(&:to_sym)
    elsif association.is_a?(Hash)
      translated_hash = {}
      association.each do |key, value|
        translated_hash[key.to_sym] = { include: json_associations(value) }
      end
      translated << translated_hash
    end
  end
end

.load_associations(payload:, associations: [], as_json_options: {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/query_helper/associations.rb', line 8

def self.load_associations(payload:, associations: [], as_json_options: {})
  as_json_options ||= {}
  as_json_options[:include] = as_json_options[:include] || json_associations(associations)
  begin
    # Preloader have been changed in Rails 7, which is giving error on upgrade.
    # This should be updated to latest API once all repos have been upgraded to Rails 7
    ActiveRecord::Associations::Preloader.new.preload(payload, associations)
  rescue
    ActiveRecord::Associations::Preloader.new(records: payload, associations: associations).call
  end
  payload.as_json(as_json_options)
end

.preload_associations(payload:, preload: []) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/query_helper/associations.rb', line 21

def self.preload_associations(payload:, preload: [])
  begin
    # Preloader have been changed in Rails 7, which is giving error on upgrade.
    # This should be updated to latest API once all repos have been upgraded to Rails 7
    ActiveRecord::Associations::Preloader.new.preload(payload, preload)
  rescue
    ActiveRecord::Associations::Preloader.new(records: payload, associations: preload).call
  end
end

.process_association_params(associations) ⇒ Object



3
4
5
6
# File 'lib/query_helper/associations.rb', line 3

def self.process_association_params(associations)
  associations ||= []
  associations.class == String ? [associations.to_sym] : associations
end