summaryrefslogtreecommitdiff
path: root/lib/banzai/lazy_reference.rb
blob: 1095b4debc76b96c3a2950e42de32958f7d144e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module Banzai
  class LazyReference
    def self.load(refs)
      lazy_references, values = refs.partition { |ref| ref.is_a?(self) }

      lazy_values = lazy_references.group_by(&:klass).flat_map do |klass, refs|
        ids = refs.flat_map(&:ids)
        klass.where(id: ids)
      end

      values + lazy_values
    end

    attr_reader :klass, :ids

    def initialize(klass, ids)
      @klass = klass
      @ids = Array.wrap(ids).map(&:to_i)
    end

    def load
      self.klass.where(id: self.ids)
    end
  end
end