summaryrefslogtreecommitdiff
path: root/lib/banzai/lazy_reference.rb
blob: 073ec5d9801f0ba466662b82a81afdb0f68f6596 (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
26
27
require 'banzai'

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