module ApiRescuable::ClassMethods

Public Instance Methods

rescue_from_api(*klasses) click to toggle source
# File lib/api_rescuable.rb, line 41
def rescue_from_api(*klasses)
  rescuer = {
    # ActiveRecord
    ActiveRecord::RecordNotFound => :handle_record_not_found,
    ActiveRecord::RecordInvalid => :handle_record_invalid,

    # Strong Params
    ActiveModel::ForbiddenAttributesError => :handle_forbidden_attributes,
    ActionController::ParameterMissing => :handle_parameter_missing,

    # Authorization
    CanCan::AccessDenied => :handle_unauthorized_access,
  }

  # Add ActiveSupport's rescue_from for all classes given in the list
  klasses.each do |klass|
    rescue_from klass, with: rescuer[klass]
  end

  # Undefine the handlers for classes not given in the list
  (rescuer.keys - klasses).each do |klass|
    undef_method rescuer[klass]
  end
end