class Userlist::Push::Serializer

Public Class Methods

serialize(resource) click to toggle source
# File lib/userlist/push/serializer.rb, line 6
def self.serialize(resource)
  new.serialize(resource)
end

Public Instance Methods

serialize(resource) click to toggle source
# File lib/userlist/push/serializer.rb, line 10
def serialize(resource)
  resource = serialize_resource(resource) if resource.is_a?(Userlist::Push::Resource)
  resource
end

Private Instance Methods

serialize_collection(collection) click to toggle source
# File lib/userlist/push/serializer.rb, line 52
def serialize_collection(collection)
  serialized = collection
    .map(&method(:serialize_relationship))
    .compact
    .reject(&:empty?)

  serialized unless serialized.empty?
end
serialize_relationship(relationship) click to toggle source
# File lib/userlist/push/serializer.rb, line 39
def serialize_relationship(relationship)
  return unless relationship

  case relationship
  when Userlist::Push::ResourceCollection
    serialize_collection(relationship)
  when Userlist::Push::Resource
    serialize_resource(relationship)
  else
    raise "Cannot serialize relationship type: #{relationship.class}"
  end
end
serialize_resource(resource) click to toggle source
# File lib/userlist/push/serializer.rb, line 17
def serialize_resource(resource)
  return resource.identifier if serialized_resources.include?(resource)

  serialized_resources << resource

  return unless resource.push?

  serialized = {}

  resource.attribute_names.each do |name|
    serialized[name] = resource.send(name)
  end

  resource.relationship_names.each do |name|
    next unless result = serialize_relationship(resource.send(name))

    serialized[name] = result
  end

  serialized
end
serialized_resources() click to toggle source
# File lib/userlist/push/serializer.rb, line 61
def serialized_resources
  @serialized_resources ||= Set.new
end