Module: Readymade::Controller::Serialization
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/readymade/controller/serialization.rb
Instance Method Summary collapse
- #collection_response(collection, *args) ⇒ Object
- #operation_response(response_obj, options = {}) ⇒ Object
- #record_response(record, *args) ⇒ Object
- #render_json(message, status) ⇒ Object
- #serialize_collection(collection, options = {}) ⇒ Object
- #serialize_record(record, options = {}) ⇒ Object
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..then do || render_json( serialize_collection(paginate(collection, ), ).merge(count: collection.count), [: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, = {}) , status = case response_obj.status.to_sym when :success, :ok [ if response_obj.data[:record].present? serialize_record(response_obj.data[:record], ) 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(, 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) = args. return render_json({}, :not_found) if record.nil? hash = serialize_record(record, ) status = if record.errors.none? [:status] || :ok else hash[:errors] = record.errors. :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(, status) render json: , status: status end |
#serialize_collection(collection, options = {}) ⇒ Object
36 37 38 39 |
# File 'lib/readymade/controller/serialization.rb', line 36 def serialize_collection(collection, = {}) serializer = .delete(:serializer) || "#{collection.klass.name}Serializer".constantize serializer.render_as_hash(collection, ) end |
#serialize_record(record, options = {}) ⇒ Object
41 42 43 44 |
# File 'lib/readymade/controller/serialization.rb', line 41 def serialize_record(record, = {}) serializer = .delete(:serializer) || "#{record.class.name}Serializer".constantize serializer.render_as_hash(record, { root: :data }.merge!()) end |