Module: ActiveModelSerializers::LookupChain

Defined in:
lib/active_model_serializers/lookup_chain.rb

Constant Summary collapse

BY_RESOURCE =

Standard appending of Serializer to the resource name.

Example:

Author => AuthorSerializer
lambda do |resource_class, _serializer_class, _namespace|
  serializer_from(resource_class)
end
BY_RESOURCE_NAMESPACE =

Uses the namespace of the resource to find the serializer

Example:

British::Author => British::AuthorSerializer
lambda do |resource_class, _serializer_class, _namespace|
  resource_namespace = namespace_for(resource_class)
  serializer_name = serializer_from(resource_class)

  "#{resource_namespace}::#{serializer_name}"
end
BY_NAMESPACE =

Uses the controller namespace of the resource to find the serializer

Example:

Api::V3::AuthorsController => Api::V3::AuthorSerializer
lambda do |resource_class, _serializer_class, namespace|
  resource_name = resource_class_name(resource_class)
  namespace ? "#{namespace}::#{resource_name}Serializer" : nil
end
BY_PARENT_SERIALIZER =

Allows for serializers to be defined in parent serializers

  • useful if a relationship only needs a different set of attributes than if it were rendered independently.

Example:

 class BlogSerializer < ActiveModel::Serializer
   class AuthorSerialier < ActiveModel::Serializer
   ...
   end

   belongs_to :author
   ...
 end

The belongs_to relationship would be rendered with
  BlogSerializer::AuthorSerialier
lambda do |resource_class, serializer_class, _namespace|
  return if serializer_class == ActiveModel::Serializer

  serializer_name = serializer_from(resource_class)
  "#{serializer_class}::#{serializer_name}"
end
DEFAULT =
[
  BY_PARENT_SERIALIZER,
  BY_NAMESPACE,
  BY_RESOURCE_NAMESPACE,
  BY_RESOURCE
].freeze

Class Method Summary collapse

Class Method Details

.namespace_for(klass) ⇒ Object



65
66
67
# File 'lib/active_model_serializers/lookup_chain.rb', line 65

def namespace_for(klass)
  klass.name.deconstantize
end

.resource_class_name(klass) ⇒ Object



69
70
71
# File 'lib/active_model_serializers/lookup_chain.rb', line 69

def resource_class_name(klass)
  klass.name.demodulize
end

.serializer_from(klass) ⇒ Object



77
78
79
80
# File 'lib/active_model_serializers/lookup_chain.rb', line 77

def serializer_from(klass)
  name = resource_class_name(klass)
  serializer_from_resource_name(name)
end

.serializer_from_resource_name(name) ⇒ Object



73
74
75
# File 'lib/active_model_serializers/lookup_chain.rb', line 73

def serializer_from_resource_name(name)
  "#{name}Serializer"
end