Sha256: d28f483f49b87a4ae0712a7f71ce953ca70942c3afcf98342746ce087ff1294c

Contents?: true

Size: 1.43 KB

Versions: 14

Compression:

Stored size: 1.43 KB

Contents

module MongoMapper
  module Plugins
    module Validations
      module InstanceMethods
        def self.included(model)
          model.class_eval { include Validatable }
        end
      end
      
      module DocumentMacros
        def validates_uniqueness_of(*args)
          add_validations(args, MongoMapper::Plugins::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?
          return true if allow_nil && value.nil?
          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 = {}
          conditions[attribute] = /#{instance[attribute].to_s}/i unless case_sensitive
          conditions
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
mongo_mapper-unstable-2010.1.22 lib/mongo_mapper/plugins/validations.rb
mongo_mapper-unstable-2010.1.21 lib/mongo_mapper/plugins/validations.rb
mongo_mapper-unstable-2010.1.20 lib/mongo_mapper/plugins/validations.rb
mongo_mapper-unstable-2010.1.19 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.7 lib/mongo_mapper/plugins/validations.rb
mongo_mapper-unstable-2010.1.18 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.6 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.5 lib/mongo_mapper/plugins/validations.rb
mongo_mapper-unstable-2010.1.17 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.4 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.2 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.1 lib/mongo_mapper/plugins/validations.rb
jmonteiro-mongo_mapper-0.1.0 lib/mongo_mapper/plugins/validations.rb
mongo_mapper-unstable-2010.1.12 lib/mongo_mapper/plugins/validations.rb