Class: DataMapper::Validate::UniquenessValidator
- Inherits:
-
GenericValidator
- Object
- GenericValidator
- DataMapper::Validate::UniquenessValidator
- Includes:
- Extlib::Assertions
- Defined in:
- lib/gems/dm-validations-0.9.9/lib/dm-validations/uniqueness_validator.rb
Overview
Instance Attribute Summary
Attributes inherited from GenericValidator
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?, #field_name
Constructor Details
#initialize(field_name, options = {}) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
11 12 13 14 15 |
# File 'lib/gems/dm-validations-0.9.9/lib/dm-validations/uniqueness_validator.rb', line 11 def initialize(field_name, = {}) assert_kind_of 'scope', [:scope], Array, Symbol if .has_key?(:scope) super @field_name, @options = field_name, end |
Instance Method Details
#call(target) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/gems/dm-validations-0.9.9/lib/dm-validations/uniqueness_validator.rb', line 17 def call(target) scope = Array(@options[:scope]) return true if @options[:allow_nil] && target.send(field_name).nil? repository_name = target.repository.name opts = { :fields => target.model.key, field_name => target.validation_property_value(field_name) } scope.each do |item| if target.model.properties(repository_name).has_property?(item) opts[item] = target.validation_property_value(item) elsif target.model.relationships(repository_name).has_key?(item) target.validation_association_keys(item).each do |key| opts[key] = target.validation_property_value(key) end end end resource = repository(repository_name) { target.model.first(opts) } return true if resource.nil? # is target and found resource identic? same instance... but not == return true if !target.new_record? && resource.repository.name == repository_name && resource.model == target.model && resource.key == target.key = @options[:message] || "%s is already taken".t(Extlib::Inflection.humanize(field_name)) add_error(target, , field_name) return false end |