~ubuntu-branches/ubuntu/saucy/ruby-validatable/saucy

1 by Cédric Boutillier
Import upstream version 1.6.7
1
module Validatable
2
  class Errors
3
    extend Forwardable
4
    include Enumerable
5
6
    def_delegators :errors, :clear, :each, :each_pair, :empty?, :length, :size
7
8
    # call-seq: on(attribute)
9
    # 
10
    # * Returns nil, if no errors are associated with the specified +attribute+.
11
    # * Returns the error message, if one error is associated with the specified +attribute+.
12
    # * Returns an array of error messages, if more than one error is associated with the specified +attribute+.
13
    def on(attribute)
14
      return nil if errors[attribute.to_sym].nil?
15
      errors[attribute.to_sym].size == 1 ? errors[attribute.to_sym].first : errors[attribute.to_sym]
16
    end
17
18
    def add(attribute, message) #:nodoc:
19
      errors[attribute.to_sym] = [] if errors[attribute.to_sym].nil?
20
      errors[attribute.to_sym] << message
21
    end
22
23
    def merge!(errors) #:nodoc:
24
      errors.each_pair{|k, v| add(k,v)}
25
      self
26
    end
27
28
    # call-seq: replace(attribute)
29
    # 
30
    # * Replaces the errors value for the given +attribute+
31
    def replace(attribute, value)
32
      errors[attribute.to_sym] = value
33
    end
34
35
    # call-seq: raw(attribute)
36
    # 
37
    # * Returns an array of error messages associated with the specified +attribute+.
38
    def raw(attribute)
39
      errors[attribute.to_sym]
40
    end
41
    
42
    def errors #:nodoc:
43
      @errors ||= {}
44
    end
45
46
    def count #:nodoc:
47
      errors.values.flatten.size
48
    end
49
50
    # call-seq: full_messages -> an_array_of_messages
51
    # 
52
    # Returns an array containing the full list of error messages.
53
    def full_messages
54
      full_messages = []
55
56
      errors.each_key do |attribute|
57
        errors[attribute].each do |msg|
58
          next if msg.nil?
59
60
          if attribute.to_s == "base"
61
            full_messages << msg
62
          else
63
            full_messages << humanize(attribute.to_s) + " " + msg
64
          end
65
        end
66
      end
67
      full_messages
68
    end
69
    
70
    def humanize(lower_case_and_underscored_word) #:nodoc:
71
      lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
72
    end
73
  end
74
end