Class: Granola::Serializer

Inherits:
Object
  • Object
show all
Includes:
Caching, Schema
Defined in:
lib/granola.rb,
lib/granola/schema.rb,
lib/granola/caching.rb

Overview

A Serializer describes how to serialize a certain type of object, by declaring the structure of JSON objects.

Defined Under Namespace

Modules: Schema

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Caching

#cache_key, #last_modified

Methods included from Schema

included, #valid?, #validation_errors

Constructor Details

#initialize(object) ⇒ Serializer

Public: Initialize the serializer with a given object.

object - The domain model that we want to serialize into JSON.


42
43
44
# File 'lib/granola.rb', line 42

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object


24
25
26
# File 'lib/granola.rb', line 24

def object
  @object
end

Class Method Details

.list(ary, *args) ⇒ Object

Public: Instantiates a list serializer that wraps around an iterable of objects of the type expected by this serializer class.

Example:

serializer = PersonSerializer.list(people)
serializer.to_json

Returns a Granola::List.


35
36
37
# File 'lib/granola.rb', line 35

def self.list(ary, *args)
  List.new(ary, *args, with: self)
end

Instance Method Details

#attributesObject

Public: Returns the Hash of attributes that should be serialized into JSON.

Raises NotImplementedError unless you override in subclasses.


50
51
52
# File 'lib/granola.rb', line 50

def attributes
  fail NotImplementedError
end

#mime_typeObject

Public: Returns the MIME type generated by this serializer. By default this will be `application/json`, but you can override in your serializers if your API uses a different MIME type (e.g. `application/my-app+json`).

Returns a String.


68
69
70
# File 'lib/granola.rb', line 68

def mime_type
  "application/json".freeze
end

#to_json(**options) ⇒ Object

Public: Generate the JSON String.

**options - Any options to be passed to the `Granola.json` Proc.

Returns a String.


59
60
61
# File 'lib/granola.rb', line 59

def to_json(**options)
  Granola.json.(attributes, options)
end