Module: Dscf::Core::JsonResponse
- Extended by:
- ActiveSupport::Concern
- Included in:
- ApplicationController, Common, ReviewableController
- 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
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'app/controllers/concerns/dscf/core/json_response.rb', line 55 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
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'app/controllers/concerns/dscf/core/json_response.rb', line 30 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 18 19 20 21 22 23 24 25 26 27 28 |
# 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 # Handle hash data with potential serializer options serialized_hash = {} data.each do |key, value| if [key] && value.is_a?(ActiveRecord::Base) # Use specific serializer for this key if provided serializer_opts = [key].is_a?(Hash) ? [key] : {} serialized_hash[key] = ActiveModelSerializers::SerializableResource.new(value, serializer_opts) else serialized_hash[key] = serialize(value, ) end end serialized_hash when Array data.map { |value| serialize(value, ) } else data end end |