Sha256: b3f260815e00fb56119162d78843bd64e835dfd8579b052da3ec78953316d2a3

Contents?: true

Size: 1.6 KB

Versions: 32

Compression:

Stored size: 1.6 KB

Contents

module ActiveUtils #:nodoc:
  module Validateable #:nodoc:
    def valid?
      errors.clear

      before_validate if respond_to?(:before_validate, true)
      validate if respond_to?(:validate, true)

      errors.empty?
    end

    def initialize(attributes = {})
      self.attributes = attributes
    end

    def errors
      @errors ||= Errors.new(self)
    end

    private

    def attributes=(attributes)
      unless attributes.nil?
        for key, value in attributes
          send("#{key}=", value )
        end
      end
    end

    # This hash keeps the errors of the object
    class Errors < HashWithIndifferentAccess

      def initialize(base)
        super() { |h, k|  h[k] = [] ; h[k] }
        @base = base
      end

      def count
        size
      end

      def empty?
        all? { |k, v| v && v.empty? }
      end

      # returns a specific fields error message.
      # if more than one error is available we will only return the first. If no error is available
      # we return an empty string
      def on(field)
        self[field].to_a.first
      end

      def add(field, error)
        self[field] << error
      end

      def add_to_base(error)
        add(:base, error)
      end

      def each_full
        full_messages.each { |msg| yield msg }
      end

      def full_messages
        result = []

        self.each do |key, messages|
          next if messages.blank?
          if key == 'base'
            result << "#{messages.first}"
          else
            result << "#{key.to_s.humanize} #{messages.first}"
          end
        end

        result
      end
    end
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
active_utils-3.4.1 lib/active_utils/validateable.rb
active_utils-3.4.0 lib/active_utils/validateable.rb
active_utils-3.3.19 lib/active_utils/validateable.rb
active_utils-3.3.18 lib/active_utils/validateable.rb
active_utils-3.3.17 lib/active_utils/validateable.rb
active_utils-3.3.16 lib/active_utils/validateable.rb
active_utils-3.3.15 lib/active_utils/validateable.rb
active_utils-3.3.14 lib/active_utils/validateable.rb
active_utils-3.3.13 lib/active_utils/validateable.rb
active_utils-3.3.12 lib/active_utils/validateable.rb
active_utils-3.3.11 lib/active_utils/validateable.rb
active_utils-3.3.10 lib/active_utils/validateable.rb
active_utils-3.3.9 lib/active_utils/validateable.rb
active_utils-3.3.8 lib/active_utils/validateable.rb
active_utils-3.3.7 lib/active_utils/validateable.rb
active_utils-3.3.6 lib/active_utils/validateable.rb
active_utils-3.3.5 lib/active_utils/validateable.rb
active_utils-3.3.4 lib/active_utils/validateable.rb
active_utils-3.3.3 lib/active_utils/validateable.rb
active_utils-3.3.2 lib/active_utils/validateable.rb