Skip to content

Instantly share code, notes, and snippets.

@mehdi-farsi
Last active December 22, 2021 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mehdi-farsi/16325b004ef6fb0bb19785871870d69b to your computer and use it in GitHub Desktop.
Save mehdi-farsi/16325b004ef6fb0bb19785871870d69b to your computer and use it in GitHub Desktop.
en:
errors:
messages:
http_unauthorized: 'Authentication required'
http_not_found: 'Not found'
http_bad_request: 'Incorrect or incomplete input'
http_service_unavailable: 'Service unavailable'
http_forbidden: 'Forbidden'
http_unprocessable_entity: 'Unprocessable Entity'
resource_not_found: 'Resource not found'
# frozen_string_literal: true
module RenderErrors
extend ActiveSupport::Concern
def errors(codes, messages = nil, data = nil)
codes = wrap(codes)
{ codes: codes, messages: wrap(messages) || messages(codes), data: wrap(data) || data(codes) }
end
def active_record_errors(active_errors)
details = active_errors.details.transform_values { |v| v.map { |p| p[:error] } }
messages = active_errors.details.map { |k, _| [k, active_errors.full_messages_for(k)] }.to_h
data = active_errors.details.transform_values { |v| v.map { |p| p.except(:error, :value) } }
errors(details, messages, data)
end
def http_status_errors(status)
errors("http_#{status}")
end
def render_http_error(status)
render status: status, json: http_status_errors(status)
end
def render_model_errors(model, status: :unprocessable_entity)
render status: status, json: active_record_errors(model.errors)
end
def render_errors(status, codes = nil, messages = nil, data = nil)
render status: status, json: errors(codes, messages, data)
end
private
def messages(codes)
codes.transform_values { |ary| ary.map { |c| c && I18n.t("errors.messages.#{c}") } }
end
def data(codes)
codes.transform_values { |ary| Array.new(ary.size, {}) }
end
def wrap(flat)
flat.nil? || flat.is_a?(Hash) ? flat : { base: [flat] }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment