Class: RailsObservatory::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_observatory/serializers/serializer.rb

Constant Summary collapse

PERMITTED_TYPES =
[NilClass, String, Integer, Float, TrueClass, FalseClass]
ADDITIONAL_SERIALIZERS =
[JobSerializer, MailDeliveryJobSerializer, EventSerializer, RequestSerializer, HeadersSerializer, ResponseSerializer]

Class Method Summary collapse

Class Method Details

.serialize(argument) ⇒ Object



18
19
20
# File 'lib/rails_observatory/serializers/serializer.rb', line 18

def serialize(argument)
  serialize_payload(argument)
end

.serialize_hash(argument) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/rails_observatory/serializers/serializer.rb', line 41

def serialize_hash(argument)
  argument.each_with_object({}) do |(key, value), hash|
    case key
    when String, Symbol
      hash[key.to_s] = serialize_payload(value)
    end
  end
end

.serialize_payload(argument) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rails_observatory/serializers/serializer.rb', line 22

def serialize_payload(argument)
  case argument
  when *PERMITTED_TYPES
    argument
  when Array
    argument.map { serialize_payload(_1) }
  when ActiveSupport::HashWithIndifferentAccess
    serialize_hash(argument)
  when Hash
    serialize_hash(argument)
  when -> (arg) { arg.respond_to?(:permitted?) && arg.respond_to?(:to_h) }
    serialize_hash(argument.to_h)
  when Symbol
    argument.to_s
  else
    ADDITIONAL_SERIALIZERS.find { argument.is_a?(_1.klass) }&.new&.serialize(argument)&.deep_stringify_keys || "Unable to serialize #{argument.class.name}"
  end
end