Class: DataMapper::Validations::UniqueValidator
- Inherits:
-
GenericValidator
- Object
- GenericValidator
- DataMapper::Validations::UniqueValidator
- Defined in:
- lib/data_mapper/validations/unique_validator.rb
Constant Summary collapse
- ERROR_MESSAGES =
{ :unique => '#{field} has already been taken' }
Instance Method Summary collapse
- #call(target) ⇒ Object
-
#initialize(field_name, options = {}) ⇒ UniqueValidator
constructor
A new instance of UniqueValidator.
- #valid?(target) ⇒ Boolean
Methods inherited from GenericValidator
#add_error, #validation_error_message
Constructor Details
#initialize(field_name, options = {}) ⇒ UniqueValidator
Returns a new instance of UniqueValidator.
10 11 12 13 |
# File 'lib/data_mapper/validations/unique_validator.rb', line 10 def initialize(field_name, = {}) @options = @field_name = field_name.to_sym end |
Instance Method Details
#call(target) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/data_mapper/validations/unique_validator.rb', line 15 def call(target) field = Inflector.humanize(@field_name) unless valid?(target) = (ERROR_MESSAGES[:unique], nil, binding) add_error(target, , @field_name) return false end return true end |
#valid?(target) ⇒ Boolean
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/data_mapper/validations/unique_validator.rb', line 27 def valid?(target) field_value = target.instance_variable_get("@#{@field_name}") return true if @options[:allow_nil] && field_value.nil? = { @field_name => field_value } if @options[:scope] scope_value = target.instance_variable_get("@#{@options[:scope]}") .merge! @options[:scope] => scope_value end .merge!({ target.session.mappings[target.class].key.name.not => target.key }) unless target.new_record? # HACK: gotta make sure we're using the same database that this instance was # found with unless new_record? target.session.find(target.class, :first, ).nil? end |