Sha256: 2d5677fb21115d29a92e0ee714ec14b5f42d2deb1da54657067a379578b646b5

Contents?: true

Size: 932 Bytes

Versions: 3

Compression:

Stored size: 932 Bytes

Contents

module Stratify
  module MongoidExtension
    module NaturalKey
      module ClassMethods
        attr_reader :natural_key_fields

        def natural_key(*fields)
          @natural_key_fields = fields.dup
          validates_uniqueness_of_natural_key
        end
        
        def validates_uniqueness_of_natural_key
          first, *rest = *natural_key_fields
          if rest.empty?
            validates_uniqueness_of first
          else
            validates_uniqueness_of first, :scope => rest
          end
        end
      end

      module InstanceMethods
        def natural_key_hash
          {}.tap do |hash|
            self.class.natural_key_fields.each do |field|
              hash[field] = self.send(field)
            end
          end
        end
      end

      def self.included(receiver)
        receiver.extend ClassMethods
        receiver.send :include, InstanceMethods
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
stratify-base-0.1.3 lib/stratify/mongoid_extension.rb
stratify-base-0.1.2 lib/stratify/mongoid_extension.rb
stratify-base-0.1.0 lib/stratify/mongoid_extension.rb