Sha256: 0dd75d3b2ab8e142be4a755c38c97de76fea96f4bee88519df7e7604efbb11a9

Contents?: true

Size: 1.21 KB

Versions: 11

Compression:

Stored size: 1.21 KB

Contents

module MongoMapper
  module Validations    
    module Macros
      def validates_uniqueness_of(*args)
        add_validations(args, MongoMapper::Validations::ValidatesUniquenessOf)
      end
    end
    
    class ValidatesUniquenessOf < Validatable::ValidationBase
      option :scope, :case_sensitive
      default :case_sensitive => true

      def valid?(instance)
        value = instance[attribute]
        return true if allow_blank && value.blank?
        base_conditions = case_sensitive ? {self.attribute => value} : {}
        doc = instance.class.first(base_conditions.merge(scope_conditions(instance)).merge(where_conditions(instance)))
        doc.nil? || instance._id == doc._id
      end

      def message(instance)
        super || "has already been taken"
      end

      def scope_conditions(instance)
        return {} unless scope
        Array(scope).inject({}) do |conditions, key|
          conditions.merge(key => instance[key])
        end
      end

      def where_conditions(instance)
        conditions = {}
        unless case_sensitive
          conditions.merge!({'$where' => "this.#{attribute}.toLowerCase() == '#{instance[attribute].downcase}'"})
        end
        conditions
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 4 rubygems

Version Path
mongo_mapper-0.6.6 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.12.4 lib/mongo_mapper/validations.rb
danielharan-mongo_mapper-0.6.5 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.5 lib/mongo_mapper/validations.rb
webbynode-mongo_mapper-0.6.4 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.4 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.3 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.2 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.1 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.11.18 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.0 lib/mongo_mapper/validations.rb