From 4ed12fd1ee6c53035d92b86991b0f5404997c5f9 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Wed, 10 Apr 2024 09:34:27 +0200 Subject: [PATCH] Lazily compute possible serializer class names There is no point computing them all and then later look them up. --- lib/active_model/serializer.rb | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 45a93b2b6..5bbd9f42f 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -68,14 +68,13 @@ def serializer_for(resource, options = {}) ArraySerializer end else - search_list = build_serializer_class_list(resource, options) - result = search_list.map do |klass_name| - Serializer.serializers_cache.fetch_or_store(klass_name) do - _const_get(klass_name) - end - end - - result.find { |serializer| !serializer.nil? } + each_possible_serializer(resource, options) do |klass_name| + serializer = Serializer.serializers_cache.fetch_or_store(klass_name) do + _const_get(klass_name) + end + return serializer unless serializer.nil? + end + nil end end @@ -124,11 +123,10 @@ def strip_attribute(attr) attr end - def build_serializer_class_list(resource, options) - list = [] - list << build_serializer_class(resource, options) - list << build_serializer_class(resource, {}) - list << build_serializer_class(resource.class.name.demodulize, {}) + def each_possible_serializer(resource, options) + yield build_serializer_class(resource, options) + yield build_serializer_class(resource, {}) + yield build_serializer_class(resource.class.name.demodulize, {}) end def build_serializer_class(resource, options)