Sha256: 8cd5a30fd7736dadcc20348ee1f86bfec9516e9b06dff83e5244072579ed5247

Contents?: true

Size: 1.69 KB

Versions: 5

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaPlugins
    module Preloads
      #
      # Finds relations to preload for provided serializer
      #
      class PreloadsConstructor
        module ClassMethods
          #
          # Constructs preloads hash for given serializer
          #
          # @param serializer [Serega] Instance of Serega serializer
          #
          # @return [Hash]
          #
          def call(map)
            return FROZEN_EMPTY_HASH unless map

            preloads = {}
            append_many(preloads, map)
            preloads
          end

          private

          def append_many(preloads, map)
            map.each do |point|
              current_preloads = point.attribute.preloads
              next unless current_preloads

              has_nested = point.has_nested_points?
              current_preloads = SeregaUtils::EnumDeepDup.call(current_preloads) if has_nested
              append_current(preloads, current_preloads)
              next unless has_nested

              nested_preloads = nested(preloads, point.preloads_path)
              append_many(nested_preloads, point.nested_points)
            end
          end

          def append_current(preloads, current_preloads)
            merge(preloads, current_preloads) unless current_preloads.empty?
          end

          def merge(preloads, current_preloads)
            preloads.merge!(current_preloads) do |_key, value_one, value_two|
              merge(value_one, value_two)
            end
          end

          def nested(preloads, path)
            (!path || path.empty?) ? preloads : preloads.dig(*path)
          end
        end

        extend ClassMethods
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
serega-0.6.1 lib/serega/plugins/preloads/lib/preloads_constructor.rb
serega-0.6.0 lib/serega/plugins/preloads/lib/preloads_constructor.rb
serega-0.5.2 lib/serega/plugins/preloads/lib/preloads_constructor.rb
serega-0.5.1 lib/serega/plugins/preloads/lib/preloads_constructor.rb
serega-0.5.0 lib/serega/plugins/preloads/lib/preloads_constructor.rb