Why a random text plugin? Just because I can. It's easy enough to implement and with just a little knowledge of Ruby and knowing how to search the internet for some JavaScript, it's a piece of cake.

I built this after seeing the Chuck Norris plugin for Octopress. While that plugin extracts JSON encoded data from the Chuck Norris database at icndb.com, I decided to go with a slightly old-fashioned approach - a flat text file, where each line is a record.

Getting the text is easy, all I had to do was to use the following JavaScript in the page.

Random text script
<p id="random-text"></p>
<script text="javascript">
var request = new XMLHttpRequest();
request.onload = function() {
    // get the file contents
    var fileContent = this.responseText;
    // split into lines
    var fileContentLines = fileContent.split( '\n' );
    // get a random index (line number)
    var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
    // extract the value
    var randomLine = fileContentLines[ randomLineIndex ];
    // add the random line in a div
    document.getElementById( 'random-text' ).innerHTML = randomLine;
request.open( 'GET', '/random-texts.txt', true );

The XMLHttpRequest is used to retrieve a file using the HTTP GET method. The onload is passed an anonymous function which retrieves the response from the GET call, splits it by newlines and picks a random line from that array. Finally, it sets the innerHTML field of the random-text paragraph to that line.

Now, I could have added the JavaScript to the template manually, but instead, it makes more sense to automatically generate it. Also, I wanted to allow multiple instances, and allow users to specify a different source file for each instance. This was accomplished by creating a new Liquid::Tag plugin and allowing the user to specify {% randomtext file:/quotes.txt %}.

The plugin creates a new ID for each instance by creating a random 8-digit number and appending it to the string random-text-. The render method for the tag uses that ID in the <p> block as well as within the JavaScript. It also extracts the file name from the tag and uses that instead of /random-texts.txt.

Also, while you can specify local files by giving the path from the root, you can also specify a file on an external website by using the full URL, such as {% randomtext file:http://www.example.com/path/to/quotes.txt %}

You can see this working on the sidebar. All you need to do is refresh the page and it will automatically display a new string. You can also see the code here.


comments powered by Disqus