Ruby on Rails Generate Random Data

Ruby on Rails Generate Random Data

Sometimes we need to programmatically generate text in Ruby on Rails. We may not have any data available to play with or we may need text in order to mock up the user interface. In this article I will cover 2 different methods of generating random text. Let’s run through this with me.

Random Letters
If you just need fill text, you can add this helper to your application helper (app/helpers/application_helper.rb):

application_helper.rb
1
2
3
4
5
6
7
8
9
10
11
module ApplicationHelper
  def random_string(length, include_uppercase = true, include_lowercase = true, include_numbers = false)
    l = []
    l.push ('a'..'z') if include_uppercase
    l.push ('A'..'Z') if include_lowercase

    l.push (0..9) if include_numbers
    l = l.map { |i| i.to_a }.flatten
    string = (0...length).map { l[rand(l.length)] }.join
  end
end

The helper has 1 required argument is length, which determines the length of the string. To generate a random string of 200 characters, call the helper like below:

1
<%= random_string(200) %>

Forgery Gem
The forgery gem provides a great way to generate random data. Not only can forgery generate random words (based off lorem ipsum), but it can also generate random email addresses, and much more. To use forgery, just include the forgery gem in your gemfile:

Gemfile
1
gem 'forgery', '0.6.0'

Then run bundle install to install the Gem.

After installing the Gem, you are ready to go to generate words:

1
<%= Forgery(:lorem_ipsum).words(100) %>

To generate a random email address:

1
<%= Forgery('internet').email_address %>

So far so good, I hope all you guys enjoy it. See ya! :)