Sha256: ca66588757fed508e00320c016ba85610ed28f71ebe77f9ccede8dbf7cd8824e

Contents?: true

Size: 1.05 KB

Versions: 2

Compression:

Stored size: 1.05 KB

Contents

module Cavalry
  class Validator
    autoload :EachValidator, 'cavalry/validator/each_validator'
    autoload :GroupValidator, 'cavalry/validator/group_validator'

    class << self
      def validate_for(*klasses)
        @klasses = klasses.map { |k| append_required_module(k) }
        @each_validators = []
        @group_validators = []
      end

      def validate_each(&block)
        @each_validators += @klasses.map {|k| EachValidator.new(k, &block) }
      end

      def validate_group(&block)
        @group_validators += @klasses.map {|k| GroupValidator.new(k, &block) }
      end

      def execute_validation
        error_records = [].tap do |res|
          res << @each_validators.map(&:validate).compact
          res << @group_validators.map(&:validate).compact
        end.flatten

        error_records.map {|e| Error.new(e) }
      end

      private

      def append_required_module(klass)
        unless klass.include?(ActiveModel::Validations)
          klass.include(ActiveModel::Validations)
        end
        klass
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cavalry-0.2.0 lib/cavalry/validator.rb
cavalry-0.1.0 lib/cavalry/validator.rb