Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make faker gem create english sentences and paragraphs

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.

like image 223
Sathish Manohar Avatar asked Apr 21 '13 13:04

Sathish Manohar


1 Answers

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(number: rand(2..10))
body  = Faker::Lorem.paragraphs(sentence_count: 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(word_count: rand(2..10)).chomp('.')
# or
title = Faker::Lorem.words(number: rand(2..10)).join(' ')

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

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

Update 2

Positional keywords deprecated in favour of keyword arguments in Faker 2.0 in 2019

Faker::Lorem reference

like image 145
Billy Chan Avatar answered Sep 28 '22 09:09

Billy Chan