Class: MiniApi::ModelResponder

Inherits:
Object
  • Object
show all
Includes:
Serialization, Translation::Message
Defined in:
lib/mini_api/model_responder.rb

Overview

class to handle json render of ActiveRecord::Base instances and ActiveModel::Model’s

Instance Method Summary collapse

Methods included from Translation::Message

#i18n_message

Methods included from Serialization

#get_error_serializer, #serialiable_body

Constructor Details

#initialize(controller, resource, options = {}) ⇒ ModelResponder

Returns a new instance of ModelResponder.



13
14
15
16
17
# File 'lib/mini_api/model_responder.rb', line 13

def initialize(controller, resource, options = {})
  @controller = controller
  @resource = resource
  @options = options
end

Instance Method Details

#respondObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mini_api/model_responder.rb', line 19

def respond
  body = {
    success: resource_has_errors? == false,
    message: message
  }

  body =
    if resource_has_errors?
      errors.merge(body)
    else
      { data: serialiable_body(@resource).as_json }.merge(body)
    end

  body = CaseTransform.response_keys(body)

  @controller.render json: body, status: status_code
end