DEV Community

Cover image for How to use Faker: My Favorite Ruby Gem
professorjrod
professorjrod

Posted on

How to use Faker: My Favorite Ruby Gem

Faker is a Ruby gem that is used for generating fake data such as names, addresses, and phone numbers.

It's also my favorite Ruby gem as of lately.

I've been finding myself making a lot of projects that need some sort of data. Usually, most people would either use an API or make their own dataset. But Faker makes it a lot simpler.

Here's how you use it:

First, install it and add the library to your script

require 'faker'
Enter fullscreen mode Exit fullscreen mode

Then, you're gonna want to check out the documentation for all of the different methods. Here's the github page

Let's make some fake identities today.

fake_person = Faker::Name.name
puts fake_person
Enter fullscreen mode Exit fullscreen mode

I'm starting with just a first name.

variable declaration

Nice! Now let's make it a bit more interesting. I'm gonna add some real-life details that a normal person would have. Again, there's lots of options just checkout the docs!

fake_person = { first_name: Faker::Name.first_name, 
last_name: Faker::Name.last_name, 
email: Faker::Internet.email, 
phone: Faker::PhoneNumber.phone_number }
puts fake_person
Enter fullscreen mode Exit fullscreen mode

console output

Nice! Its coming along nicely.
A lot of the time when I'm using the Faker gem, I'm usually creating a database seed or something. So let's try that here. I'm just going to put it in a loop.

10.times do |i|
  fake_person = { first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email,
                  phone: Faker::PhoneNumber.phone_number }
  puts "Person #{i + 1}: #{fake_person}"
end
Enter fullscreen mode Exit fullscreen mode

console output

Awesome! This is the power of Faker! Isn't that cool? A bunch of fake identities. You could create a fake world out of them!

Try using faker in your next project! It's a lot of fun. Also, I added an Escape from Tarkov category for all you Tarkov fans out there with a TON of in game categories so stay tuned for the next release!

HAPPY CODING!

Top comments (0)