Sha256: 54ffe400cd8be6c8a3c7fb2e1c52591b4449dd2481f50b28c1d6edf1e43bf454

Contents?: true

Size: 1.35 KB

Versions: 6

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

class Serega
  class Map
    module ClassMethods
      def call(opts)
        @cache ||= {}
        cache_key = opts.to_s

        @cache[cache_key] ||= begin
          modifiers = {
            only: opts&.[](:only) || FROZEN_EMPTY_HASH,
            except: opts&.[](:except) || FROZEN_EMPTY_HASH,
            with: opts&.[](:with) || FROZEN_EMPTY_HASH
          }

          construct_map(serializer_class, **modifiers).tap do
            @cache.shift if @cache.length >= serializer_class.config[:max_cached_map_per_serializer_count]
          end
        end
      end

      private

      def construct_map(serializer_class, only:, except:, with:)
        serializer_class.attributes.each_with_object([]) do |(name, attribute), map|
          next unless attribute.visible?(only: only, except: except, with: with)

          nested_map =
            if attribute.relation?
              construct_map(
                attribute.serializer,
                only: only[name] || FROZEN_EMPTY_HASH,
                with: with[name] || FROZEN_EMPTY_HASH,
                except: except[name] || FROZEN_EMPTY_HASH
              )
            else
              FROZEN_EMPTY_ARRAY
            end

          map << [attribute, nested_map]
        end
      end
    end

    extend ClassMethods
    extend Serega::Helpers::SerializerClassHelper
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
serega-0.1.5 lib/serega/map.rb
serega-0.1.4 lib/serega/map.rb
serega-0.1.3 lib/serega/map.rb
serega-0.1.2 lib/serega/map.rb
serega-0.1.1 lib/serega/map.rb
serega-0.1.0 lib/serega/map.rb