Module: BetterController::Serializer

Extended by:
ActiveSupport::Concern
Defined in:
lib/better_controller/serializer.rb

Overview

Base module for serializing resources

Instance Method Summary collapse

Instance Method Details

#serialize(resource, options = {}) ⇒ Hash

Serialize a resource

Parameters:

  • resource (Object)

    The resource to serialize

  • options (Hash) (defaults to: {})

    Serialization options

Returns:

  • (Hash)

    The serialized resource



38
39
40
41
42
43
44
45
46
# File 'lib/better_controller/serializer.rb', line 38

def serialize(resource, options = {})
  return nil if resource.nil?

  if resource.respond_to?(:each) && !resource.is_a?(Hash)
    serialize_collection(resource, options)
  else
    serialize_resource(resource, options)
  end
end

#serialize_collection(collection, options = {}) ⇒ Array<Hash>

Serialize a collection of resources

Parameters:

  • collection (Array, ActiveRecord::Relation)

    The collection to serialize

  • options (Hash) (defaults to: {})

    Serialization options

Returns:

  • (Array<Hash>)

    The serialized collection



52
53
54
# File 'lib/better_controller/serializer.rb', line 52

def serialize_collection(collection, options = {})
  collection.map { |resource| serialize_resource(resource, options) }
end

#serialize_resource(resource, options = {}) ⇒ Hash

Serialize a single resource

Parameters:

  • resource (Object)

    The resource to serialize

  • options (Hash) (defaults to: {})

    Serialization options

Returns:

  • (Hash)

    The serialized resource



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/better_controller/serializer.rb', line 60

def serialize_resource(resource, options = {})
  result = {}

  # Add attributes
  self.class.attributes.each do |attr|
    result[attr] = resource.send(attr) if resource.respond_to?(attr)
  end

  # Add methods
  self.class.methods.each do |meth|
    result[meth] = resource.send(meth) if resource.respond_to?(meth)
  end

  # Add associations
  self.class.associations.each do |name, serializer_class|
    next unless resource.respond_to?(name)

    association  = resource.send(name)
    serializer   = serializer_class.new
    result[name] = serializer.serialize(association, options)
  end

  result
end