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

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(message_key = nil, status: :unprocessable_entity, errors: nil, **options)
  response = {
    success: false
  }

  if message_key
    response[:error] = I18n.t(message_key)
  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!(options)

  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(message_key = nil, data: nil, status: :ok, serializer_options: {}, **options)
  response = {success: true}

  if message_key
    response[:message] = I18n.t(message_key)
  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, serializer_options)
    response[:data] = serialized_data
  end

  # Add pagination metadata if present (handled by Common concern)
  response[:pagination] = serializer_options[:pagination] if serializer_options[:pagination]

  response.merge!(options)
  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, options = {})
  case data
  when ActiveRecord::Base, ActiveRecord::Relation
    ActiveModelSerializers::SerializableResource.new(data, options)
  when Hash
    # Handle hash data with potential serializer options
    serialized_hash = {}
    data.each do |key, value|
      if options[key] && value.is_a?(ActiveRecord::Base)
        # Use specific serializer for this key if provided
        serializer_opts = options[key].is_a?(Hash) ? options[key] : {}
        serialized_hash[key] = ActiveModelSerializers::SerializableResource.new(value, serializer_opts)
      else
        serialized_hash[key] = serialize(value, options)
      end
    end
    serialized_hash
  when Array
    data.map { |value| serialize(value, options) }
  else
    data
  end
end