diff --git a/Rakefile b/Rakefile index 612bd06..2fd3e17 100644 --- a/Rakefile +++ b/Rakefile @@ -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 diff --git a/lib/uniquify.rb b/lib/uniquify.rb index d4da9cf..ccd4106 100644 --- a/lib/uniquify.rb +++ b/lib/uniquify.rb @@ -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 diff --git a/uniquify.gemspec b/uniquify.gemspec index e0aad38..ffff299 100644 --- a/uniquify.gemspec +++ b/uniquify.gemspec @@ -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"]