Sha256: c62e35609469364dddee534def1e4cc3702f2c36ae976b3bca8514c3758effb0

Contents?: true

Size: 1.61 KB

Versions: 2

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

module ActiveRecordDataLoader
  module ActiveRecord
    class PolymorphicBelongsToConfiguration
      def self.config_for(polymorphic_settings:)
        ar_association = polymorphic_settings.model_class.reflect_on_association(
          polymorphic_settings.name
        )
        raise "#{name} only supports polymorphic associations" unless ar_association.polymorphic?

        new(polymorphic_settings, ar_association).polymorphic_config
      end

      def initialize(settings, ar_association)
        @settings = settings
        @ar_association = ar_association
        @model_count = settings.weighted_models.size
      end

      def polymorphic_config
        {
          @ar_association.foreign_type.to_sym => ->(row_number) { foreign_type(row_number) },
          @ar_association.foreign_key.to_sym => ->(row_number) { foreign_key(row_number) },
        }
      end

      private

      def foreign_type(row_number)
        possible_values[row_number % @model_count][0]
      end

      def foreign_key(row_number)
        possible_values[row_number % @model_count][1].sample
      end

      def possible_values
        @possible_values ||= begin
          values = @settings.models.keys.map do |klass|
            [klass.name, base_query(klass).pluck(klass.primary_key).to_a]
          end.to_h

          @settings.weighted_models.map { |klass| [klass.name, values[klass.name]] }
        end
      end

      def base_query(klass)
        if @settings.queries[klass].respond_to?(:call)
          @settings.queries[klass].call.all
        else
          klass.all
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_record_data_loader-1.2.0 lib/active_record_data_loader/active_record/polymorphic_belongs_to_configuration.rb
active_record_data_loader-1.1.0 lib/active_record_data_loader/active_record/polymorphic_belongs_to_configuration.rb