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


63
64
65
# File 'lib/active_model_serializers/lookup_chain.rb', line 63

def namespace_for(klass)
  klass.name.deconstantize
end

.resource_class_name(klass) ⇒ Object


67
68
69
# File 'lib/active_model_serializers/lookup_chain.rb', line 67

def resource_class_name(klass)
  klass.name.demodulize
end

.serializer_from(klass) ⇒ Object


75
76
77
78
# File 'lib/active_model_serializers/lookup_chain.rb', line 75

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

.serializer_from_resource_name(name) ⇒ Object


71
72
73
# File 'lib/active_model_serializers/lookup_chain.rb', line 71

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