Class: SimpleCommandDispatcher::Commands::CommandCallable::Errors

Inherits:
Hash
  • Object
show all
Defined in:
lib/simple_command_dispatcher/commands/errors.rb

Overview

Error collection for CommandCallable commands. Stores validation errors as a hash where keys are field names and values are arrays of error messages.

Instance Method Summary collapse

Instance Method Details

#add(key, value, _opts = {}) ⇒ Array

Adds an error message to the specified field. Automatically prevents duplicate messages for the same field.

Examples:

errors.add(:email, 'is required')
errors.add(:email, 'is invalid')
errors[:email] # => ['is required', 'is invalid']

Parameters:

  • key (Symbol, String)

    the field name

  • value (String)

    the error message

  • _opts (Hash) (defaults to: {})

    reserved for future use

Returns:

  • (Array)

    the updated array of error messages for this field



26
27
28
29
30
# File 'lib/simple_command_dispatcher/commands/errors.rb', line 26

def add(key, value, _opts = {})
  self[key] ||= []
  self[key] << value
  self[key].uniq!
end

#add_multiple_errors(errors_hash) ⇒ Object

Adds multiple errors from a hash. Values can be single messages or arrays of messages.

Examples:

errors.add_multiple_errors(email: 'is required', password: ['is too short', 'is too weak'])

Parameters:

  • errors_hash (Hash)

    hash of field names to error message(s)



39
40
41
42
43
# File 'lib/simple_command_dispatcher/commands/errors.rb', line 39

def add_multiple_errors(errors_hash)
  errors_hash.each do |key, values|
    CommandCallable::Utils.array_wrap(values).each { |value| add key, value }
  end
end

#each {|field, message| ... } ⇒ Object

Iterates over each field and message pair. If a field has multiple messages, yields once for each message.

Examples:

errors.each { |field, message| puts "#{field}: #{message}" }

Yield Parameters:

  • field (Symbol)

    the field name

  • message (String)

    the error message



53
54
55
56
57
# File 'lib/simple_command_dispatcher/commands/errors.rb', line 53

def each
  each_key do |field|
    self[field].each { |message| yield field, message }
  end
end

#full_messagesArray<String>

Returns an array of formatted error messages. Messages are prefixed with the capitalized field name, except for :base.

Examples:

errors.add(:email, 'is required')
errors.add(:base, 'Something went wrong')
errors.full_messages # => ['Email is required', 'Something went wrong']

Returns:

  • (Array<String>)

    formatted error messages



68
69
70
# File 'lib/simple_command_dispatcher/commands/errors.rb', line 68

def full_messages
  map { |attribute, message| full_message(attribute, message) }
end