Sha256: ddb9492eb9a7147b8e6fab5218c25e721c7f6e6fa48056e1955da84384821d8f

Contents?: true

Size: 1.16 KB

Versions: 3

Compression:

Stored size: 1.16 KB

Contents

module Sequel
  class Model
    # Errors represents validation errors, a simple hash subclass
    # with a few convenience methods.
    class Errors < ::Hash
      ATTRIBUTE_JOINER = ' and '.freeze

      # Assign an array of messages for each attribute on access
      def [](k)
        has_key?(k) ? super : (self[k] = [])
      end

      # Adds an error for the given attribute.
      def add(att, msg)
        self[att] << msg
      end

      # Return the total number of error messages.
      def count
        values.inject(0){|m, v| m + v.length}
      end
       
      # Return true if there are no error messages, false otherwise.
      def empty?
        count == 0
      end
      
      # Returns an array of fully-formatted error messages.
      def full_messages
        inject([]) do |m, kv| 
          att, errors = *kv
          errors.each {|e| m << "#{Array(att).join(ATTRIBUTE_JOINER)} #{e}"}
          m
        end
      end
      
      # Returns the array of errors for the given attribute, or nil
      # if there are no errors for the attribute.
      def on(att)
        if v = fetch(att, nil) and !v.empty?
          v
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
sequel-3.13.0 lib/sequel/model/errors.rb
sequel-3.12.1 lib/sequel/model/errors.rb
sequel-3.12.0 lib/sequel/model/errors.rb