Sha256: 2d3a0015a2c6abc0e91ab1321c03e37bb6329d9180dc61dbb7d7b261771f4092

Contents?: true

Size: 1.45 KB

Versions: 3

Compression:

Stored size: 1.45 KB

Contents

module Gizzard
  module Base
    extend ActiveSupport::Concern

    class_methods do
      def preload_associations(records:, associations:, scope: nil)
        records = Array(records)
        return if records.empty?

        if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new(7)
          ActiveRecord::Associations::Preloader.new(records: records, associations: associations, scope: scope).call
        else
          ActiveRecord::Associations::Preloader.new.preload(records, associations, scope)
        end
      end

      def delete_all_by_id(batch_size: 1000)
        ids = pluck(:id)
        ids.sort!
        ids.each_slice(batch_size) do |chunked_ids|
          # unscoped入れないと既に適用されているスコープが引き継がれる
          unscoped.all.where(id: chunked_ids).delete_all
        end
      end

      def less_than_id(id)
        less_than(:id, id)
      end

      def greater_than_id(id)
        greater_than(:id, id)
      end

      def less_than(key, value)
        value.present? ? all.where(arel_table[key].lt(value)) : all
      end

      def less_than_equal(key, value)
        value.present? ? all.where(arel_table[key].lteq(value)) : all
      end

      def greater_than(key, value)
        value.present? ? all.where(arel_table[key].gt(value)) : all
      end

      def greater_than_equal(key, value)
        value.present? ? all.where(arel_table[key].gteq(value)) : all
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
gizzard-0.9.1 lib/gizzard/base.rb
gizzard-0.9.0 lib/gizzard/base.rb
gizzard-0.8.0 lib/gizzard/base.rb