class Cuprum::Rails::MapErrors

Maps errors from a validated Rails model to a Stannum::Errors object.

Public Class Methods

instance() click to toggle source

@return [MapErrors] a memoized instance of the class.

# File lib/cuprum/rails/map_errors.rb, line 11
def self.instance
  @instance ||= new
end

Public Instance Methods

call(native_errors:) click to toggle source

Maps an ActiveModel::Errors object to a Stannum::Errors object.

@param native_errors [ActiveModel::Errors] The Rails error object.

@return [Stannum::Errors] the generated errors object.

# File lib/cuprum/rails/map_errors.rb, line 20
def call(native_errors:)
  unless native_errors.is_a?(ActiveModel::Errors)
    raise ArgumentError,
      'native_errors must be an instance of ActiveModel::Errors'
  end

  map_errors(native_errors: native_errors)
end

Private Instance Methods

map_errors(native_errors:) click to toggle source
# File lib/cuprum/rails/map_errors.rb, line 31
def map_errors(native_errors:)
  errors = Stannum::Errors.new

  native_errors.each do |error|
    attribute = error.attribute
    scoped    = attribute == :base ? errors : errors[attribute]

    scoped.add(error.type, message: error.message, **error.options)
  end

  errors
end