Class: DataMapper::Validate::UniquenessValidator
- Inherits:
-
GenericValidator
- Object
- GenericValidator
- DataMapper::Validate::UniquenessValidator
- Includes:
- Extlib::Assertions
- Defined in:
- lib/dm-validations/validators/uniqueness_validator.rb
Overview
Instance Attribute Summary
Attributes inherited from GenericValidator
#field_name, #humanized_field_name, #if_clause, #options, #unless_clause
Instance Method Summary collapse
- #call(target) ⇒ Object
-
#initialize(field_name, options = {}) ⇒ UniquenessValidator
constructor
A new instance of UniquenessValidator.
Methods inherited from GenericValidator
#==, #add_error, #execute?, #inspect
Constructor Details
#initialize(field_name, options = {}) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
11 12 13 14 15 16 |
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 11 def initialize(field_name, = {}) assert_kind_of 'scope', [:scope], Array, Symbol if .has_key?(:scope) super @options[:allow_nil] = true unless @options.include?(:allow_nil) end |
Instance Method Details
#call(target) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 18 def call(target) value = target.send(field_name) return true if @options[:allow_nil] && value.blank? 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? return true if target.saved? && resource.key == target.key = @options[:message] || ValidationErrors.(:taken, field_name) add_error(target, , field_name) false end |