Sha256: 25fd58c193b2b16aa01ed4fc5ffb5f393a91bbd2498f44b702f9fe2af7a96f7d

Contents?: true

Size: 906 Bytes

Versions: 1

Compression:

Stored size: 906 Bytes

Contents

module Validatable
  class ValidatesUniquenessOf < ValidationBase
    option :scope, :allow_nil, :case_sensitive

    def message(instance)
      super || '%s has already been taken'.t(humanized_attribute)
    end
    
    def case_sensitive?
      case_sensitive
    end
    
    def valid?(instance)
      value = instance.send(self.attribute)
      return true if allow_nil && value.nil?
      
      finder_options = if case_sensitive?
        { self.attribute => value }
      else
        { self.attribute.like => value }
      end
      
      if scope
        scope_value = instance.send(scope)
        finder_options.merge! scope => scope_value
      end
      
      finder_options.merge!({ instance.database_context.table(instance.class).key.name.not => instance.key }) unless instance.new_record?
      instance.database_context.first(instance.class, finder_options).nil?
    end  
  end
  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
datamapper-0.2.4 lib/data_mapper/validatable_extensions/validations/validates_uniqueness_of.rb