Introduction

Sometimes we need to programmatically generate text in Ruby on Rails. For instance, we may not have any data available to play with or we may need text in order to mock up a user interface. In this short article we will cover 2 different methods of generating random text. Let’s get started.

Method One: Pure Random Letters

If you just need filler text, you can simply add this helper to your application helper:

app/helpers/application_helper.rb:

module ApplicationHelper
  def random_string(length, include_uppercase = true, include_lowercase = true, include_numbers = false)
    o = []
    o.push ('a'..'z') if include_uppercase
    o.push ('A'..'Z') if include_lowercase
    
    o.push (0..9) if include_numbers
    o = o.map { |i| i.to_a }.flatten
    string = (0...length).map { o[rand(o.length)] }.join
  end
end

The helper has 1 required argument, length, which determines the length of the string. The rest of the arguments determine which combinations of letters and numbers are in the string. For example, to generate a random string of 160 characters, call the helper like this:


<%= random_string(160) %>

To only include uppercase letters, simply pass false to the include_uppercase and include_numbers params:


<%= random_string(160, false, true, false) %>

That's great and all, but what if we need actual words? We could attempt to modify the function above to add spaces, etc. However, there is a better solution.

Method Two: The 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, monetary amounts, and much more. To use forgery, just include the forgery gem in your gemfile:

Gemfile:

gem 'forgery', '~> 0.6.0'

After running a bundle install you are ready to go! To generate words, simply use forgery like so:


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

To generate a random email address, simply use Forgery like so:


<%= Forgery(:internet).email_address %>

Forgery has absolutely dozens of generators for everything from names to street addresses, random colors, and much more. For more information be sure to checkout the forgery github page at https://github.com/sevenwire/forgery.

That's it! Thanks for reading!