module Validators
  class Base

    def initialize(model, options={})
      @model = model
      @options = options
    end

    def validate!
      raise Devops::Exception::ValidationError.new(message) unless valid?
    rescue StandardError => e
      raise Devops::Exception::ValidationError.new("An error raised during validation with #{self.class}: #{e.class}: #{e.message}")
    end

    def valid?
      raise 'override me'
    end

    def message
      raise 'override me'
    end

    def error_class
      self.class.get_error_class
    end

    class << self
      def get_error_class
        @error_class || InvalidRecord
      end

      private

      def error_class(klass)
        @error_class = klass
      end

      # this method delegates @valid? and @message methods to helper validator, passed as block
      def delegate_to_helper_validator(&block)

        define_method :helper_validator do
          @helper_validator ||= self.instance_eval(&block)
        end

        define_method :valid? do
          self.helper_validator.valid?
        end

        define_method :message do
          self.helper_validator.message
        end
      end
    end

  end
end
