Sha256: 94b5460d802a6b8208b8ad7bb5688f6d50a669c473440bee7a44a203efb54de2

Contents?: true

Size: 919 Bytes

Versions: 1

Compression:

Stored size: 919 Bytes

Contents

# frozen_string_literal: true

module ActiveRecordDataLoader
  module ActiveRecord
    class List
      def self.for(enumerable, strategy: :random)
        if strategy == :random_cycle
          RandomCycle.new(enumerable)
        else
          Random.new(enumerable)
        end
      end

      class Random
        def initialize(enumerable)
          @list = enumerable
        end

        def next
          @list.sample
        end
      end

      class RandomCycle
        def initialize(enumerable)
          @enumerable = enumerable
          @count = enumerable.count
          reset_list
        end

        def next
          value = @list.next
          reset_list if (@index += 1) >= @count
          value
        end

        private

        def reset_list
          @index = 0
          @enumerable = @enumerable.shuffle
          @list = @enumerable.cycle
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_record_data_loader-1.3.1 lib/active_record_data_loader/active_record/list.rb