Ruby - Fun with Faker

Have you ever been stuck with the need to pick some random names? Or addresses maybe?

Faker have you covered! On the Github page of Faker you can find a huge lists of strings it can generate: names, addresses and even coffee blends.

For example let’s say we want some coffee.

require 'faker'
puts "Today I will have some coffee\nwith #{Faker::Coffee::notes} flavour\ncalled #{Faker::Coffee::blend_name}\nfrom #{Faker::Coffee::origin}."
$ irb
2.4.1 :001 > require 'faker'
 => true 
2.4.1 :002 > puts "Today I will have some coffee\nwith #{Faker::Coffee::notes} flavour\ncalled #{Faker::Coffee::blend_name}\nfrom #{Faker::Coffee::origin}."
Today I will have some coffee
with deep, creamy, watermelon, fresh bread, lavender flavour
called Kreb-Full-o Cup
from Cerrado, Brazil.
 => nil 
2.4.1 :003 > 

What just happened is that Faker generated few random (but cleverly crafted to match the data type) strings for:

  • Coffee flavors and general notes via Faker::Coffee::notes
  • Coffee blend names via Faker::Coffee::blend_name
  • Coffee origin locations via Faker::Coffee::origin

What I’m doing here is using the Faker namespace to dynamically call the methods that return the data I need. Let’s say for example that I also want to add a location where I am having my coffee. That’s easy! Just use the Faker::Address::city.

require 'faker'
puts "Today I will have some\n#{Faker::Coffee::blend_name} coffee\nat #{Faker::Address::city}."

Some more examples:

"Looking to read a #{Faker::Book::genre.downcase} book. Any ideas?"
"I just got a new book called '#{Faker::Book::title}'."
"I am #{Faker::Zelda::character}! Welcome to #{Faker::Zelda::game}!"

You can have a lot of fun with this. And every time you need some test data to work with think of Faker.

Categories:

Updated: