Skip to content

b264/unique

Repository files navigation

Build Status

unique

A lightweight Ruby gem with zero dependencies that prevents a block from returning the same object twice.

Setup

Add it to your project's Gemfile (preferred) or

$ gem install unique

Usage

require 'unique'

Unique.next! do
  #...
end

Example

1.9.3-p551 :001 > Unique.next!{ rand(5) }
 => 0
1.9.3-p551 :002 > Unique.next!{ rand(5) }
 => 4
1.9.3-p551 :003 > Unique.next!{ rand(5) }
 => 1
1.9.3-p551 :004 > Unique.next!{ rand(5) }
 => 2
1.9.3-p551 :005 > Unique.next!{ rand(5) }
 => 3
1.9.3-p551 :006 > Unique.next!{ rand(5) }
Unique::NoUniqueObjects: An unused, unique object could not be found in 4096 tries (["(irb)", 6])
  from /home/devbox/code/unique/lib/unique.rb:22:in `block in next!'
  from /home/devbox/code/unique/lib/unique.rb:20:in `loop'
  from /home/devbox/code/unique/lib/unique.rb:20:in `next!'
  from (irb):6
  from /home/devbox/.rvm/rubies/ruby-1.9.3-p551/bin/irb:12:in `<main>'
1.9.3-p551 :007 >

Config

The maximum number of times the block will be yielded looking for a unique object. Default is 4096.

Unique.max_tries= 10

Cleanup

Unique.reset! will clear previous objects and allow them to be used. This is useful in your test suite's before blocks.

Example

1.9.3-p551 :001 > Unique.next!{ rand(1) }
 => 0
1.9.3-p551 :002 > Unique.next!{ rand(1) }
Unique::NoUniqueObjects: An unused, unique object could not be found in 4096 tries (["(irb)", 2])
  from /home/devbox/code/unique/lib/unique.rb:22:in `block in next!'
  from /home/devbox/code/unique/lib/unique.rb:20:in `loop'
  from /home/devbox/code/unique/lib/unique.rb:20:in `next!'
  from (irb):6
  from /home/devbox/.rvm/rubies/ruby-1.9.3-p551/bin/irb:12:in `<main>'
1.9.3-p551 :003 > Unique.reset!
 => []
1.9.3-p551 :004 > Unique.next!{ rand(1) }
 => 0

Is it any good?

Yes

License

ISC

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages