Class: DataMapper::Validations::UniquenessValidator
- Inherits:
-
GenericValidator
- Object
- GenericValidator
- DataMapper::Validations::UniquenessValidator
- Includes:
- 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.
- #valid?(target) ⇒ Boolean
Methods inherited from GenericValidator
#==, #add_error, #evaluate_conditional_clause, #execute?, #inspect, #optional?, #set_optional_by_default
Constructor Details
#initialize(field_name, options = {}) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
9 10 11 12 13 14 15 16 17 |
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 9 def initialize(field_name, = {}) if .has_key?(:scope) assert_kind_of('scope', [:scope], Array, Symbol) end super set_optional_by_default end |
Instance Method Details
#call(target) ⇒ Object
19 20 21 22 23 24 25 26 |
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 19 def call(target) return true if valid?(target) = @options[:message] || ValidationErrors.(:taken, field_name) add_error(target, , field_name) false end |
#valid?(target) ⇒ Boolean
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/dm-validations/validators/uniqueness_validator.rb', line 28 def valid?(target) value = target.validation_property_value(field_name) return true if optional?(value) opts = { :fields => target.model.key(target.repository.name), field_name => value, } Array(@options[:scope]).each { |subject| unless target.respond_to?(subject) raise(ArgumentError,"Could not find property to scope by: #{subject}. Note that :unique does not currently support arbitrarily named groups, for that you should use :unique_index with an explicit validates_uniqueness_of.") end opts[subject] = target.__send__(subject) } resource = DataMapper.repository(target.repository.name) do target.model.first(opts) end return true if resource.nil? target.saved? && resource.key == target.key end |