Module: Readymade::Controller::Serialization

Extended by:
ActiveSupport::Concern
Defined in:
lib/readymade/controller/serialization.rb

Instance Method Summary collapse

Instance Method Details

#collection_response(collection, *args) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/readymade/controller/serialization.rb', line 23

def collection_response(collection, *args)
  args.extract_options!.then do |options|
    render_json(
      serialize_collection(paginate(collection, options), options).merge(count: collection.count),
      options[:status] || :ok
    )
  end
end

#operation_response(response_obj, options = {}) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/readymade/controller/serialization.rb', line 46

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, :fail
                      [{ errors: response_obj.data[:errors] }, :bad_request]
                    else
                      [response_obj.status.to_sym, {}]
                    end
  render_json(message, status)
end

#record_response(record, *args) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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) ⇒ Object



32
33
34
# File 'lib/readymade/controller/serialization.rb', line 32

def render_json(message, status)
  render json: message, status: status
end

#serialize_collection(collection, options = {}) ⇒ Object



36
37
38
39
# File 'lib/readymade/controller/serialization.rb', line 36

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 = {}) ⇒ Object



41
42
43
44
# File 'lib/readymade/controller/serialization.rb', line 41

def serialize_record(record, options = {})
  serializer = options.delete(:serializer) || "#{record.class.name}Serializer".constantize
  serializer.render_as_hash(record, { root: :data }.merge!(options))
end