class Cuprum::Rails::Serializers::Json::Serializer

Converts objects or data structures to JSON based on configured serializers.

Public Class Methods

instance() click to toggle source

@return [Cuprum::Rails::Serializers::Json::Serializer] a cached instance

of the serializer.
# File lib/cuprum/rails/serializers/json/serializer.rb, line 16
def self.instance
  @instance ||= new
end

Public Instance Methods

call(object, serializers:) click to toggle source

Converts the object to JSON using the given serializers.

First, call finds the best serializer from the :serializers Hash. This is done by walking up the object class’s ancestors to find the closest ancestor which is a key in the :serializers Hash. The corresponding value is then called with the object.

@param object [Object] The object to convert to JSON. @param serializers [Hash<Class, call>] The serializers for different

object types.

@return [Object] a JSON-compatible representation of the object.

@raise RecursiveSerializerError if the serializer would create an infinite

loop, e.g. by calling itself.

@raise UndefinedSerializerError if there is no matching serializer for

the object.
# File lib/cuprum/rails/serializers/json/serializer.rb, line 37
def call(object, serializers:)
  serializer = handle_recursion!(object) do
    serializer_for(object: object, serializers: serializers)
  end

  serializer.call(object, serializers: serializers)
end

Private Instance Methods

handle_recursion!(object) { || ... } click to toggle source
# File lib/cuprum/rails/serializers/json/serializer.rb, line 47
def handle_recursion!(object)
  serializer = yield

  return serializer unless instance_of?(serializer.class)

  raise RecursiveSerializerError,
    "invalid serializer for #{object.class.name} - recursive calls to" \
    " #{self.class.name}#call"
end
serializer_for(object:, serializers:) click to toggle source
# File lib/cuprum/rails/serializers/json/serializer.rb, line 57
def serializer_for(object:, serializers:)
  object.class.ancestors.each do |ancestor|
    return serializers[ancestor] if serializers.key?(ancestor)
  end

  raise UndefinedSerializerError,
    "no serializer defined for #{object.class.name}"
end