# frozen_string_literal: true class Serega module SeregaPlugins module Lazy def self.plugin_name :lazy end def self.before_load_plugin(serializer_class, **opts) end def self.load_plugin(serializer_class, **_opts) serializer_class.extend(ClassMethods) serializer_class.include(InstanceMethods) end def self.after_load_plugin(serializer_class, **_opts) serializer_class.config.attribute_keys << :lazy end end module ClassMethods def lazy(key:, buffer:, resolver:) @lazy[key] = { buffer: buffer, resolver: resolver } end end module InstanceMethods def initialize(*args, **kwargs) super @lazy = {} end def to_h(*args, **kwargs) result = super lazy.each_key do |key, | buffer = lazy.delete(key) # { val => [paths], val2 => [paths2] } buffer_values = self.class.lazy[key][:resolver].(buffer.keys) buffer_values.each do |key, resolved_value| paths = buffer[key] paths.each do |path| result.dig(path[0, -2]) replace(result, buffer_values) end end end register_plugin(Metadata.plugin_name, Metadata) end end