module Readymade::Controller::Serialization

Public Instance Methods

collection_response(collection, *args) click to toggle source
# File lib/readymade/controller/serialization.rb, line 23
def collection_response(collection, *args)
  options = args.extract_options!

  render_json(
    {
      items: serialize_collection(paginate(collection, options), options),
      count: collection.count
    },
    options[:status] || :ok
  )
end
operation_response(response_obj, options = {}) click to toggle source
# File lib/readymade/controller/serialization.rb, line 49
def operation_response(response_obj, options = {})
  message, status = case response_obj.status.to_sym
                    when :success, :ok
                      [
                        if response_obj.data[:record].present?
                          serialize_record(response_obj.data[:record],
                                           options)
                        else
                          {}
                        end,
                        :ok
                      ]
                    when :validation_fail, :bad_request
                      [{ errors: response_obj.data[:errors] }, :bad_request]
                    else
                      [response_obj.status.to_sym, {}]
                    end
  render_json(message, status)
end
record_response(record, *args) click to toggle source
# File lib/readymade/controller/serialization.rb, line 8
def record_response(record, *args)
  options = args.extract_options!
  return render_json({}, :not_found) if record.nil?

  hash = serialize_record(record, options)

  status = if record.errors.none?
             options[:status] || :ok
           else
             hash[:errors] = record.errors.messages
             :bad_request
           end
  render_json(hash, status)
end
render_json(message, status) click to toggle source
# File lib/readymade/controller/serialization.rb, line 35
def render_json(message, status)
  render json: message, status: status
end
serialize_collection(collection, options = {}) click to toggle source
# File lib/readymade/controller/serialization.rb, line 39
def serialize_collection(collection, options = {})
  serializer = options.delete(:serializer) || "#{collection.klass.name}Serializer".constantize
  serializer.render_as_hash(collection, options)
end
serialize_record(record, options = {}) click to toggle source
# File lib/readymade/controller/serialization.rb, line 44
def serialize_record(record, options = {})
  serializer = options.delete(:serializer) || "#{record.class.name}Serializer".constantize
  serializer.render_as_hash(record, { root: :data }.merge!(options))
end