Class: PatternQueryHelper::Associations

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

Class Method Summary collapse

Class Method Details

.json_associations(associations) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pattern_query_helper/associations.rb', line 18

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



12
13
14
15
16
# File 'lib/pattern_query_helper/associations.rb', line 12

def self.load_associations(payload, associations, as_json_options)
  ActiveRecord::Associations::Preloader.new.preload(payload, associations)
  as_json_options ||= { include: json_associations(associations) }
  payload.as_json(as_json_options)
end

.process_association_params(associations) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/pattern_query_helper/associations.rb', line 3

def self.process_association_params(associations)
  associations ||= []
  if associations.class == String
    [associations.to_sym]
  else
    associations
  end
end