Sha256: d43a547819f792b4a54e932f2b2f5826a81446b7a90a197db9b11deb3677cd3c

Contents?: true

Size: 884 Bytes

Versions: 4

Compression:

Stored size: 884 Bytes

Contents

# frozen_string_literal: true

module ActiveRecordDataLoader
  module ActiveRecord
    class BelongsToConfiguration
      def self.config_for(ar_association:, query: nil)
        raise "#{name} does not support polymorphic associations" if ar_association.polymorphic?

        { ar_association.join_foreign_key.to_sym => new(ar_association, query).foreign_key_func }
      end

      def initialize(ar_association, query)
        @ar_association = ar_association
        @query = query
      end

      def foreign_key_func
        -> { possible_values.sample }
      end

      private

      def possible_values
        @possible_values ||= base_query.pluck(@ar_association.join_primary_key).to_a
      end

      def base_query
        if @query&.respond_to?(:call)
          @query.call.all
        else
          @ar_association.klass.all
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
active_record_data_loader-1.0.2 lib/active_record_data_loader/active_record/belongs_to_configuration.rb
active_record_data_loader-1.0.1 lib/active_record_data_loader/active_record/belongs_to_configuration.rb
active_record_data_loader-1.0.0 lib/active_record_data_loader/active_record/belongs_to_configuration.rb
active_record_data_loader-0.1.2 lib/active_record_data_loader/active_record/belongs_to_configuration.rb