Class: Objective::Errors::ErrorMessageCreator

Inherits:
Object
  • Object
show all
Defined in:
lib/objective/errors/error_message_creator.rb

Constant Summary collapse

MESSAGES =
Hash.new('is invalid').tap do |h|
  h.merge!(
    nils: 'cannot be nil',

    string: 'must be a string',
    integer: 'must be an integer',
    decimal: 'must be a number',
    boolean: 'must be a boolean',
    hash: 'must be a hash',
    array: 'must be an array',
    model: 'must be the right class',
    date: 'date does non exist',

    empty: 'cannot be empty',
    matches: 'has an incorrect format',
    in: 'is not an available option',
    min: 'is too small',
    max: 'is too big',
    new_records: 'model must be saved'
  )
end

Instance Method Summary collapse

Instance Method Details

#index_ordinal(index) ⇒ Object



38
39
40
41
# File 'lib/objective/errors/error_message_creator.rb', line 38

def index_ordinal(index)
  return if index.nil?
  ordinalize_index(index)
end

#message(atom, parent_key, index) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/objective/errors/error_message_creator.rb', line 28

def message(atom, parent_key, index)
  [
    index_ordinal(index),
    (atom.key || parent_key || 'item').to_s,
    MESSAGES[atom.codes]
  ]
    .compact
    .join(' ')
end

#ordinalize_index(index) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/objective/errors/error_message_creator.rb', line 43

def ordinalize_index(index)
  number = index + 1

  ordinal =
    if (11..13).cover?(number % 100)
      'th'
    else
      case number % 10
      when 1 then 'st'
      when 2 then 'nd'
      when 3 then 'rd'
      else 'th'
      end
    end

  "#{number}#{ordinal}"
end