Sha256: b37f2800dea80c29eec9a06c8f1bf7b3b3d69f99c093b7d9a5d166b4bc58c422

Contents?: true

Size: 1.22 KB

Versions: 8

Compression:

Stored size: 1.22 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].to_s.downcase}'"})
        end
        conditions
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 3 rubygems

Version Path
tpitale-mongo_mapper-0.6.9 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.12.29 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.12.23 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.12.22 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.12.16 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.8 lib/mongo_mapper/validations.rb
mongo_mapper-unstable-2009.12.14 lib/mongo_mapper/validations.rb
mongo_mapper-0.6.7 lib/mongo_mapper/validations.rb