#632 ✓resolved
Xavier Shay

[PATCH] Add unique generation to dm-sweatshop

Reported by Xavier Shay | November 2nd, 2008 @ 03:41 PM

At the moment there is no way to generate unique data using sweatshop. This specced and documented patch fixes this. From the README:

Data for fields with a uniqueness constraint (for example, e-mail addresses) can be generated using the unique method. The simplest usage is to guarantee that random data is unique - wrap your generator in a unique block with no parameters, and the block will be repeatedly executed until it generates a unique value (don't worry, it raises after a few tries).

For repeatable data, provide a block with one parameter. An incrementing value will be passed in on each invocation of that block. You can also name a unique block to override the block's identity (yeah that sentence is dense, just see the examples).

include DataMapper::Sweatshop::Unique # Use DataMapper::Sweatshop.unique if you don't want to pollute your namespace

User.fix {{
  :name  => unique { /\w+/.gen }
  :email => unique {|x| "person-#{x}@example.com" }

[User.gen.email, User.gen.email]
# => ["person-0@example.com", "person-1@example.com"]

names = ['bob', 'tom', 'bob']
Person.fix {{
  :name  => (name = names.shift)
  :email => unique(name) {|x| "#{name}-#{x}@example.com" }

[Person.gen.email, Person.gen.email, Person.gen.email]
# => ["bob-0@example.com", "tom-0@example.com", "bob-1@example.com"]

There are extra examples in the source code documentation.

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

People watching this ticket