Class: ActiveModel::Errors

Inherits:
Object
  • Object
show all
Defined in:
lib/russian/active_model_ext/custom_error_message.rb

Instance Method Summary collapse

Instance Method Details

#full_message(attribute, message) ⇒ Object

Redefine the ActiveModel::Errors.full_messages method:

Returns all the full error messages in an array. 'Base' messages are handled as usual.
Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^'
in which case the attribute name is omitted.
E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/russian/active_model_ext/custom_error_message.rb', line 12

def full_message(attribute, message)
  return message if attribute == :base
  attr_name = attribute.to_s.tr('.', '_').humanize
  attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
  
  if message =~ /^\^/
    message[1..-1]
  else
    I18n.t(:"errors.format", {
      default:  "%{attribute} %{message}",
      attribute: attr_name,
      message:   message
    })
  end
end

#to_hash(full_messages = false) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/russian/active_model_ext/custom_error_message.rb', line 29

def to_hash(full_messages = false)
  if full_messages
    self.to_hash_old.each_with_object({}) do |(attribute, array), messages|
      messages[attribute] = array.map { |message| full_message(attribute, message) }
    end
  else
    self.to_hash_old.map do |k, vs|
      m = vs.map do |v|
        if v =~ /^\^/
          v[1..-1]
        else
          v
        end
      end
      {k => m}
    end.reduce(:merge)
  end
end

#to_hash_oldObject



28
# File 'lib/russian/active_model_ext/custom_error_message.rb', line 28

alias_method :to_hash_old, :to_hash