Sha256: eb69cf65c193d9a0f090bc9eb4177117bf611fd221ef1a2aaa7f1b8a5da66538

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

module MongoMapper
  module Plugins
    module Validations
      def self.configure(model)
        model.class_eval { include Validatable }

        if defined?(ActiveModel)
          # this methods are not defined when using rails 3
          class << model
            [:validate, :validate_on_update, :validate_on_create].each do |method|
              define_method(method) do |*args, &block|
                set_callback(method, *args, &block)
              end
            end
          end
        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

1 entries across 1 versions & 1 rubygems

Version Path
drogus-mongo_mapper-0.6.10 lib/mongo_mapper/plugins/validations.rb