Class: Granola::List

Inherits:
Serializer show all
Defined in:
lib/granola.rb,
lib/granola/caching.rb

Overview

Internal: The List serializer provides an interface for serializing lists of objects, wrapping around a specific serializer.

Example:

serializer = Granola::List.new(people, PersonSerializer)
serializer.to_json

You should use Serializer.list instead of this class.

Instance Attribute Summary collapse

Attributes inherited from Serializer

#object

Instance Method Summary collapse

Methods inherited from Serializer

list, #mime_type, #to_json

Methods included from Serializer::Schema

included, #valid?, #validation_errors

Constructor Details

#initialize(list, *args, with: serializer) ⇒ List

Public: Instantiate a new list serializer.

list - An Array-like structure. *args - Any other arguments that the item serializer takes.

Keywords:

with: The subclass of Granola::Serializer to use when serializing
      specific elements in the list.

94
95
96
97
# File 'lib/granola.rb', line 94

def initialize(list, *args, with: serializer)
  @item_serializer = with
  @list = list.map { |obj| @item_serializer.new(obj, *args) }
end

Instance Attribute Details

#item_serializerObject (readonly)

Internal: Get the serializer class to use for each item of the list.


84
85
86
# File 'lib/granola.rb', line 84

def item_serializer
  @item_serializer
end

Instance Method Details

#attributesObject

Public: Returns an Array of Hashes that can be serialized into JSON.


100
101
102
# File 'lib/granola.rb', line 100

def attributes
  @list.map(&:attributes)
end

#cache_keyObject


28
29
30
31
# File 'lib/granola/caching.rb', line 28

def cache_key
  all = @list.map(&:cache_key).compact
  all.join("-") if all.any?
end

#last_modifiedObject


33
34
35
# File 'lib/granola/caching.rb', line 33

def last_modified
  @list.map(&:last_modified).compact.sort.last
end