How make faker gem create english sentences and paragraphs

Sathish Manohar picture Sathish Manohar · Apr 21, 2013 · Viewed 7k times · Source

I use following code in lib/tasks/sample_data.rake file to generate fake data to fill development database.

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    Faker::Config.locale = :en
    99.times do |n|
      title  = Faker::Lorem.words(2..10)
      body  = Faker::Lorem.paragraphs(2..8)
      Topic.create!(title: title,
                   body: body)
    end
  end
end

The problem is the generated text for title looks like this in index page

--- - doloribus - numquam - placeat - delectus - et - vero
--- - nostrum - numquam - laudantium - voluptas - est - laborum
--- - perferendis - nemo - facilis - quis - eos - quia - sint 

There are unnecessary hiphens in the generated output, This also happens in the generated paragraphs. As shown below.

--- - Fuga explicabo et ea. Excepturi earum ut consequatur minima iure.  
Molestias id tempora alias quisquam animi earum. Eius libero minima ut.  
Repudiandae eum commodi. - Iure aliquam at maxime. Rerum ea non corrupti  
asperiores est. Debitis suscipit nihil quod ut eaque sint repellat.   
quae doloremque. - Voluptatem facere deleniti nisi libero. Molestiae 
magni dolores repudiandae in corporis. Ut enim illum optio et architecto.

How do I prevent this behavior of adding unnecessary hyphens, and create clean looking English statements and paragraphs with faker gem.

Thanks.

Answer

Billy Chan picture Billy Chan · Apr 21, 2013

I don't think Faker methods accept range as arguments. In doc it only accepts numbers. Thus I can't even reproduce your problem in console by copying your code.

Maybe you want to generate words or paragraphs in random length? You can use rand to generate it. Like this:

title = Faker::Lorem.words(rand(2..10))
body  = Faker::Lorem.paragraphs(rand(2..8))

Update

Faker will create HASH instead of plain string.

So, for your title, you'd better use sentence instead of words and then chomp the last .

title = Faker::Lorem.sentence(rand(2..10)).chomp('.')
# or
title = Faker::Lorem.words(rand(2..10)).join(' ')

For body, join the paragraphs with \n or whatever you like

body  = Faker::Lorem.paragraphs(rand(2..8)).join('\n')