Module: Dscf::Core::JsonResponse
- Extended by:
- ActiveSupport::Concern
- Included in:
- ApplicationController, Common
- Defined in:
- app/controllers/concerns/dscf/core/json_response.rb
Instance Method Summary collapse
- #render_error(message_key = nil, status: :unprocessable_entity, errors: nil, **options) ⇒ Object
- #render_success(message_key = nil, data: nil, status: :ok, serializer_options: {}, **options) ⇒ Object
- #serialize(data, options = {}) ⇒ Object
Instance Method Details
#render_error(message_key = nil, status: :unprocessable_entity, errors: nil, **options) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'app/controllers/concerns/dscf/core/json_response.rb', line 44 def render_error( = nil, status: :unprocessable_entity, errors: nil, **) response = { success: false } if response[:error] = I18n.t() else model_key = @clazz&.name&.demodulize&.underscore action_key = action_name i18n_key = "#{model_key}.errors.#{action_key}" response[:error] = I18n.t(i18n_key) if I18n.exists?(i18n_key) end response[:errors] = errors if errors response.merge!() render json: response, status: status end |
#render_success(message_key = nil, data: nil, status: :ok, serializer_options: {}, **options) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'app/controllers/concerns/dscf/core/json_response.rb', line 19 def render_success( = nil, data: nil, status: :ok, serializer_options: {}, **) response = {success: true} if response[:message] = I18n.t() else model_key = @clazz&.name&.demodulize&.underscore action_key = action_name i18n_key = "#{model_key}.success.#{action_key}" response[:message] = I18n.t(i18n_key) if I18n.exists?(i18n_key) end if data serialized_data = serialize(data, ) response[:data] = serialized_data end # Add pagination metadata if present (handled by Common concern) response[:pagination] = [:pagination] if [:pagination] response.merge!() render json: response, status: status end |
#serialize(data, options = {}) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'app/controllers/concerns/dscf/core/json_response.rb', line 6 def serialize(data, = {}) case data when ActiveRecord::Base, ActiveRecord::Relation ActiveModelSerializers::SerializableResource.new(data, ) when Hash data.transform_values { |value| serialize(value, ) } when Array data.map { |value| serialize(value, ) } else data end end |