Sha256: 32938d61ca9e1b836dac3e683efa1a0d59012a154a2f561ca73f0b7fc8c281d0

Contents?: true

Size: 1.6 KB

Versions: 6

Compression:

Stored size: 1.6 KB

Contents

module DataMapper
  module Validations

    ##
    #
    # @author Guy van den Berg
    # @since  0.9
    class UniquenessValidator < GenericValidator
      include DataMapper::Assertions

      def initialize(field_name, options = {})
        assert_kind_of 'scope', options[:scope], Array, Symbol if options.has_key?(:scope)
        super

        set_optional_by_default
      end

      def call(target)
        return true if valid?(target)

        error_message = @options[:message] || ValidationErrors.default_error_message(:taken, field_name)
        add_error(target, error_message, field_name)

        false
      end

      def valid?(target)
        value = target.validation_property_value(field_name)
        return true if optional?(value)

        opts = {
          :fields    => target.model.key,
          field_name => value,
        }

        Array(@options[:scope]).each { |subject| opts[subject] = target.__send__(subject) }

        resource = DataMapper.repository(target.repository.name) { target.model.first(opts) }

        return true if resource.nil?

        target.saved? && resource.key == target.key
      end
    end # class UniquenessValidator

    module ValidatesUniqueness
      extend Deprecate

      # Validate the uniqueness of a field
      #
      def validates_uniqueness_of(*fields)
        opts = opts_from_validator_args(fields)
        add_validator_to_context(opts, fields, DataMapper::Validations::UniquenessValidator)
      end

      deprecate :validates_is_unique, :validates_uniqueness_of

    end # module ValidatesIsUnique
  end # module Validations
end # module DataMapper

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
dm-validations-1.0.2 lib/dm-validations/validators/uniqueness_validator.rb
dm-validations-1.0.1 lib/dm-validations/validators/uniqueness_validator.rb
dm-validations-1.0.0 lib/dm-validations/validators/uniqueness_validator.rb
dm-validations-1.0.0.rc3 lib/dm-validations/validators/uniqueness_validator.rb
dm-validations-1.0.0.rc2 lib/dm-validations/validators/uniqueness_validator.rb
dm-validations-1.0.0.rc1 lib/dm-validations/validators/uniqueness_validator.rb