Skip to content

Instantly share code, notes, and snippets.

@lukemelia
Created January 21, 2022 18:52
Show Gist options
  • Save lukemelia/aefe8fde7e8e2be5d6e4fa4fab74fecf to your computer and use it in GitHub Desktop.
Save lukemelia/aefe8fde7e8e2be5d6e4fa4fab74fecf to your computer and use it in GitHub Desktop.
Standalone model serialization with JSON::API Resources
class SerializeToJsonapi
DEFAULT_OPTIONS = {
serialization_options: { suppress_self_link: true }
}
def initialize(
model,
resource_class,
serialization_options = {},
serialization_context = {}
)
@model = model
@resource_class = resource_class
@serialization_options = DEFAULT_OPTIONS.merge(serialization_options)
@serialization_context = serialization_context
end
def perform
resource = @resource_class.new(@model, @serialization_context)
JSONAPI::ResourceSerializer.new(
@resource_class,
@serialization_options
).serialize_to_hash(resource)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment