Skip to content
This repository was archived by the owner on Dec 12, 2021. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions lib/uniquify.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ def self.included(base)
def ensure_unique(name)
begin
self[name] = yield
end while self.class.exists?(name => self[name])
end while uniquify_exists?(name)
end

def uniquify_exists?(name)
self.class.scoped(:conditions => { name => self[name] }).exists?
end

module ClassMethods
Expand All @@ -15,7 +19,7 @@ def uniquify(*args, &block)
options = { :length => 8, :chars => ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a }
options.merge!(args.pop) if args.last.kind_of? Hash
args.each do |name|
before_validation :on => :create do |record|
before_validation :on => :create do |record|
if block
record.ensure_unique(name, &block)
else
Expand All @@ -30,6 +34,26 @@ def uniquify(*args, &block)
end
end

class ActiveRecord::Base
include Uniquify
if defined?(ActiveRecord)
class ActiveRecord::Base
include Uniquify
end
end

if defined?(DataMapper)
module Uniquify
def uniquify_exists?(name)
not self.class.all(name => self[name]).empty?
end

module ClassMethods
def before_validation options = {}, &block
self.class_eval do
before :create do
block.call(self)
end
end
end
end
end
end