Sha256: abff4a28957ff6d1d9581d01ab1ec6200c07a3e83fffc0ca925290750f7af905

Contents?: true

Size: 1.34 KB

Versions: 3

Compression:

Stored size: 1.34 KB

Contents

require 'validatable'

module CouchSurfer
  module Validations
    module ClassMethods
      def validates_uniqueness_of *args
        # add view, validation and before callbacks
        options = args.last.is_a?(Hash) ? args.pop : {}
        field = args.first
        class_eval do
          #view_by *args
          validates_true_for args.first, :logic => lambda { is_unique?(field, options) }, :message => options[:message] || "is taken"
        end
      end
    end
    
    module InstanceMethods
      def is_unique?(field, options)
        if options[:view]
          view_name = options[:view]
          query     = options[:query].is_a?(Proc) ? self.instance_eval(&options[:query]) : nil
        end
        view_name ||= "by_#{field}"
        query ||= {:key => self.send(field)}
        result = self.class.send(view_name, query)
        if result.blank?
          return true
        else
          return !id.blank? && (id == result.first.id)
        end
      end
      
      def validate_instance
        throw(:halt, false) unless valid?
      end
    end

    def self.included(receiver)
      receiver.extend ClassMethods
      receiver.send :include, Validatable
      receiver.send :include, InstanceMethods
      receiver.class_eval do
        [:save].each do |method|
          before method, :validate_instance
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
couch_surfer-0.3.4 lib/couch_surfer/validations.rb
couch_surfer-0.3.3 lib/couch_surfer/validations.rb
couch_surfer-0.3.2 lib/couch_surfer/validations.rb