Module: Serial::RailsHelpers

Defined in:
lib/serial/rails_helpers.rb

Overview

Helpers for using Serial with Rails.

Instance Method Summary collapse

Instance Method Details

#serialize(context = self, model) {|builder, model| ... } ⇒ Object

Find the serializer for `model` and serialize it in the context of self.

Examples:

serializing a single object

render json: { person: serialize(Person.first) }

serializing multiple objects

render json: { people: serialize(Person.all) }

serializing with explicit context

render json: { people: serialize(presenter, Person.all) }

serializing with explicit serializer

render json: { people: serialize(Person.all, &my_serializer) }

Parameters:

  • context (#instance_exec) (defaults to: self)
  • model (#model_name, #each?)

Yields:

  • (builder, model)

    yields if a block is given to use a custom serializer

Yield Parameters:


23
24
25
26
27
28
29
30
31
32
# File 'lib/serial/rails_helpers.rb', line 23

def serialize(context = self, model, &serializer)
  serializer &&= Serializer.new(&serializer)
  serializer ||= "#{model.model_name}Serializer".constantize

  if model.respond_to?(:map)
    serializer.map(context, model)
  else
    serializer.call(context, model)
  end
end