Sha256: 29c36940f2bbb5ee4a57c82ad85279a86cae00df45cb097e499d032e47dd68df

Contents?: true

Size: 1.2 KB

Versions: 3

Compression:

Stored size: 1.2 KB

Contents

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

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

    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
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
query_helper-0.1.1 lib/query_helper/associations.rb
query_helper-0.1.0 lib/query_helper/associations.rb
query_helper-0.0.0 lib/query_helper/associations.rb