Skip to content
This repository was archived by the owner on Dec 12, 2021. It is now read-only.
Open
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ require 'rubygems'
require 'rake'
require 'echoe'

Echoe.new('uniquify', '0.1.0') do |p|
Echoe.new('uniquify', '0.2.0') do |p|
p.description = "Generate a unique token with Active Record."
p.url = "http://github.com/ryanb/uniquify"
p.author = "Ryan Bates"
p.email = "ryan@railscasts.com"
p.author = ["Ryan Bates", "Peter Brindisi"]
p.email = ["ryan@railscasts.com", "npj@frestyl.com"]
p.ignore_pattern = ["tmp/*", "script/*"]
p.development_dependencies = []
end
Expand Down
27 changes: 17 additions & 10 deletions lib/uniquify.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,37 @@ def self.included(base)
base.extend ClassMethods
end

def ensure_unique(name)
begin
self[name] = yield
end while self.class.exists?(name => self[name])
end

module ClassMethods

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

class_inheritable_reader(:uniquify_options)
write_inheritable_attribute(:uniquify_options, options)

args.each do |name|
before_validation :on => :create do |record|
if block
record.ensure_unique(name, &block)
else
record.ensure_unique(name) do
Array.new(options[:length]) { options[:chars].to_a[rand(options[:chars].to_a.size)] }.join
end
record.ensure_unique(name)
end
end
end
end


def generate_unique
Array.new(uniquify_options[:length]) { uniquify_options[:chars].to_a[rand(uniquify_options[:chars].to_a.size)] }.join
end
end

def ensure_unique(name, &block)
begin
self[name] = (block ? block.call : self.class.generate_unique)
end while self.class.exists?(name => self[name])

self[name]
end
end

Expand Down
2 changes: 1 addition & 1 deletion uniquify.gemspec
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Gem::Specification.new do |s|
s.name = %q{uniquify}
s.version = "0.1.0"
s.version = "0.2.0"

s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version=
s.authors = ["Ryan Bates"]
Expand Down