Generate Faker Data Optionally

92 views
Skip to first unread message

Natalie Blackburn

unread,
Aug 23, 2014, 5:26:26 PM8/23/14
to ruby-...@googlegroups.com
Hey all!

I'm writing a rake task to use Faker to fill a test database. It's a lot of names, addresses, etc. for venue locations. A lot of these are mandatory, but some are optional. I'd love to have an easy way to have Faker randomly fill or not fill any of the optional fields. Has anyone done this or have good suggestions on how to make it happen? At this point we're looking at just hard coding a few with the optional fields and that doesn't seem optimal.

Thanks for any insight!

Conrad Taylor

unread,
Aug 23, 2014, 6:33:21 PM8/23/14
to ruby-...@googlegroups.com
Natalie, you can easily use something like the following to optionally set the optional variables:

def set_optional_variable?
  rand(1_000_000) % 2 == 0 ? true : false
end

some_optional_variable = set_optional_variable? ? some_faker_value : nil

--

Think different and code well,

-Conrad

Sent from my iPhone
--
You received this message because you are subscribed to the Google Groups "Ruby Faker" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-faker+...@googlegroups.com.
To post to this group, send email to ruby-...@googlegroups.com.
Visit this group at http://groups.google.com/group/ruby-faker.
For more options, visit https://groups.google.com/d/optout.

Dave Smylie

unread,
Aug 24, 2014, 12:31:59 AM8/24/14
to ruby-...@googlegroups.com
Nothing built directly into faker afaik, but ... you could just create an array of the optional fields and their types - then use rand() to determine a random number of optional fields to fill, rand() again to determine which fields from the array these should be, and then use faker to actually populate these fields.


--

dmxhzg...@gmail.com

unread,
Apr 10, 2016, 11:40:10 AM4/10/16
to Ruby Faker
For example email is required and first name and last name are optional:

100.times do
  user = User.new
  user.email = Faker::Internet.email
  user.first_name = Faker::Name.first_name if Faker::Boolean.boolean
  user.last_name = Faker::Name.last_name if Faker::Boolean.boolean
  user.save!
end
Reply all
Reply to author
Forward
0 new messages