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
):
1 2 3 4 5 6 7 8 9 10 11 |
|
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
|
|
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:
1
|
|
Then run bundle install
to install the Gem.
After installing the Gem, you are ready to go to generate words:
1
|
|
To generate a random email address:
1
|
|
So far so good, I hope all you guys enjoy it. See ya! :)