Thu 10 July 2008
Rotoscope Cannonball Productions Meticulous Boboroshi & Kynz

masthead image

boboroshi.com - fitter. happier. more 70s wallpaper.

In migrating out of MovableType I had to leave the [dark miserable depressing] world of PHP behind. So I had to rewrite some scripts in Ruby. One of said scripts is a piece of code that selects an entry from an array and returns it to the body of the code so that you can have an area that updates pretty quickly.

This was one of the first things I learned to do in PHP (thanks to Waldo patience and direction). That code was pretty simple, but not very readable or elegant:

<?php

// called by
// <?php echo $contents[$random_key]["text"]; ?>
// <?php echo $contents[$random_key]["image"]; ?>

// Gimme a number, any number

srand ((float) microtime() * 10000000);

// Define the array

$contents[0][image] = '...';
$contents[0][text] = '...';
...

// Choose your poison

$random_key = array_rand($contents);

?>

Not very elegant. It works, but it’s just nasty. In Ruby it’s pretty straight forward and I figured someone else learning ruby might be able to learn from this:

#! /usr/bin/env ruby

class RandomImage

  PHOTOS = [ # Define the array of photos. Maybe eventually do this with YAML
    #  Image Name                  Caption
    [ '930lights.jpg',             'Caption' ],
    [ 'arlingtonclouds.jpg',       'Caption' ],
        ... # Repeat 24 times
    ]

  def show_random_image
    # Select the array entry
    @photo = PHOTOS[rand(24)]

    # Give some local variables
    filename = @photo[0]
    caption = @photo[1]

    # Echo statement definitions
    random_image_call = "<img src=\"media/images/design/masthead/#{filename}\" alt=\"masthead image\" height=\"250\" width=\"725\" border=\"0\" />" 
    random_image_caption = "#{caption}" 
  end
end

You have an array defined. To get to an entry in the array you would type @photo[n] to get to the filename or caption you’d add the second level of access @photo[n][0]. Since we want the caption to match the photo, we only want to run rand once. Put that into a variable, and then operate on that variable.

Muy sexy.

Things to do in the future

  1. Make this a Mephisto plugin
  2. Use YAML instead of an inline array
  3. Get rich off the proceeds

Okay, so two out of three wouldn’t be bad.

Leave a Reply