Sha256: b1fbb1615f7d5c7c61b49e97b66a81d346814bf360c7a670b43e3d93568ee4b7

Contents?: true

Size: 979 Bytes

Versions: 20

Compression:

Stored size: 979 Bytes

Contents

# frozen_string_literal: true

module MiniDefender::HandlesValidationErrors
  extend ActiveSupport::Concern

  included do
    rescue_from MiniDefender::ValidationError, with: :handle_validation_error
  end

  private

  def handle_validation_error(error)
    unless self.respond_to?(:respond_to)
      return render json: { message: error.message, errors: error.errors }, status: :unprocessable_entity
    end

    respond_to do |format|
      format.html do
        flash[:error] = error.message
        flash[:validation_errors] = error.errors
        flash[:old_values] = safe_values

        redirect_back fallback_location: '/'
      end

      format.json do
        render json: { message: error.message, errors: error.errors }, status: :unprocessable_entity
      end
    end
  end

  def safe_values
    forbidden_keys = %w[password password_confirmation]

    params.to_unsafe_h
      .deep_stringify_keys
      .reject { |k, _| forbidden_keys.include?(k) }
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
mini_defender-0.6.8 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.7 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.5 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.4 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.3 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.2 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.1 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.6.0 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.8 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.7 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.6 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.5 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.4 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.3 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.2 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.1 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.5.0 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.4.1 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.4.0 lib/mini_defender/handles_validation_errors.rb
mini_defender-0.3.14 lib/mini_defender/handles_validation_errors.rb