mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
This adds namespace lookup to serializer_for (#1968)
* This adds namespace lookup to serializer_for * address rubocop issue * address @bf4's feedback * add docs * update docs, add more tests * apparently rails master doesn't have before filter * try to address serializer cache issue between tests * update cache for serializer lookup to include namespace in the key, and fix the tests for explicit namespace * update docs, and use better cache key creation method * update docs [ci skip] * update docs [ci skip] * add to changelog [ci skip]
This commit is contained in:
committed by
GitHub
parent
b709cd41e6
commit
b29395b0ac
@@ -44,7 +44,7 @@ module ActiveModel
|
||||
elsif resource.respond_to?(:to_ary)
|
||||
config.collection_serializer
|
||||
else
|
||||
options.fetch(:serializer) { get_serializer_for(resource.class) }
|
||||
options.fetch(:serializer) { get_serializer_for(resource.class, options[:namespace]) }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -59,13 +59,14 @@ module ActiveModel
|
||||
end
|
||||
|
||||
# @api private
|
||||
def self.serializer_lookup_chain_for(klass)
|
||||
def self.serializer_lookup_chain_for(klass, namespace = nil)
|
||||
chain = []
|
||||
|
||||
resource_class_name = klass.name.demodulize
|
||||
resource_namespace = klass.name.deconstantize
|
||||
serializer_class_name = "#{resource_class_name}Serializer"
|
||||
|
||||
chain.push("#{namespace}::#{serializer_class_name}") if namespace
|
||||
chain.push("#{name}::#{serializer_class_name}") if self != ActiveModel::Serializer
|
||||
chain.push("#{resource_namespace}::#{serializer_class_name}")
|
||||
|
||||
@@ -84,11 +85,14 @@ module ActiveModel
|
||||
# 1. class name appended with "Serializer"
|
||||
# 2. try again with superclass, if present
|
||||
# 3. nil
|
||||
def self.get_serializer_for(klass)
|
||||
def self.get_serializer_for(klass, namespace = nil)
|
||||
return nil unless config.serializer_lookup_enabled
|
||||
serializers_cache.fetch_or_store(klass) do
|
||||
|
||||
cache_key = ActiveSupport::Cache.expand_cache_key(klass, namespace)
|
||||
serializers_cache.fetch_or_store(cache_key) do
|
||||
# NOTE(beauby): When we drop 1.9.3 support we can lazify the map for perfs.
|
||||
serializer_class = serializer_lookup_chain_for(klass).map(&:safe_constantize).find { |x| x && x < ActiveModel::Serializer }
|
||||
lookup_chain = serializer_lookup_chain_for(klass, namespace)
|
||||
serializer_class = lookup_chain.map(&:safe_constantize).find { |x| x && x < ActiveModel::Serializer }
|
||||
|
||||
if serializer_class
|
||||
serializer_class
|
||||
|
||||
Reference in New Issue
Block a user