diff options
Diffstat (limited to 'lib/banzai/lazy_reference.rb')
-rw-r--r-- | lib/banzai/lazy_reference.rb | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/lib/banzai/lazy_reference.rb b/lib/banzai/lazy_reference.rb new file mode 100644 index 00000000000..073ec5d9801 --- /dev/null +++ b/lib/banzai/lazy_reference.rb @@ -0,0 +1,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 |