class DashOverlord::Serializers::Base

Constants

RAILS_HTTP_STATUS

Attributes

object[R]
options[R]

Public Class Methods

attributes() click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 89
def self.attributes
  @attributes ||= (superclass.respond_to?(:attributes) \
    ? (superclass.attributes || [])
    : []
  ).dup
end
expose(attribute, config = {}) click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 85
def self.expose(attribute, config = {})
  attributes << [attribute, { as: attribute }.merge(config)]
end
new(object, options = {}) click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 96
def initialize(object, options = {})
  @object, @options = object, options
end
root(root_name) click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 74
def self.root(root_name)
  @root_name = root_name
end
root_name() click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 78
def self.root_name
  @root_name ||= (superclass.respond_to?(:root_name) \
    ? (superclass.root_name || '')
    : ''
  ).dup
end
serialize(object, options) click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 68
def self.serialize(object, options)
  data = self.new(object, options).serialize

  (root_name != '') ? { root_name => data } : data
end
to_hash(context, method = nil, options = {}) click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 57
def self.to_hash(context, method = nil, options = {})
  object = method ? context.send(method) : context

  hash = (method == false) ? { data: nil } : serialize(object, options)

  hash.merge \
    code: RAILS_HTTP_STATUS[context.status.to_sym],
    status: context.status,
    message: context.error.message
end

Public Instance Methods

serialize() click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 102
def serialize
  object.respond_to?(:map) ? _serialize_array : _serialize_hash
end

Protected Instance Methods

_serialize_array() click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 108
def _serialize_array
  object.map do |single_object|
    self.class.new(single_object, options).serialize
  end
end
_serialize_hash() click to toggle source
# File lib/dash_overlord/serializers/base.rb, line 114
def _serialize_hash
  self.class.attributes.each_with_object({}) do |(method, config), hash|
    next if config[:if] && !send(config[:if])

    data = respond_to?(method) ? send(method) : object.send(method)

    hash[config[:as]] =
      config[:using] ? config[:using].new(data, options).serialize : data
  end
end