Sha256: 2f8c90cf4d379e6731166a25e7ba8a851da6c3770e290ef34643e3b7ee20060e

Contents?: true

Size: 991 Bytes

Versions: 3

Compression:

Stored size: 991 Bytes

Contents

module Spira
  module Validations
    class UniquenessValidator < ActiveModel::EachValidator
      # Unfortunately, we have to tie Uniqueness validators to a class.
      def setup(klass)
        @klass = klass
      end

      def validate_each(record, attribute, value)
        @klass.find_each(:conditions => {attribute => value}) do |other_record|
          if other_record.subject != record.subject
            record.errors.add(attribute, "is already taken")
            break
          end
        end
      end
    end

    module ClassMethods
      # Validates whether the value of the specified attributes are unique across the system.
      # Useful for making sure that only one user
      # can be named "davidhh".
      #
      #   class Person < Spira::Base
      #     validates_uniqueness_of :user_name
      #   end
      #
      def validates_uniqueness_of(*attr_names)
        validates_with UniquenessValidator, _merge_attributes(attr_names)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
spira-0.7.1 lib/spira/validations/uniqueness.rb
spira-0.7 lib/spira/validations/uniqueness.rb
spira-0.5.0 lib/spira/validations/uniqueness.rb