DEV Community

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

Posted on

4

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay