Understanding Plain Text Story File Hierarchy

June 20, 2008

Plain text stories have quite alot of infrastructure that allows you to run the story file. I'm being pretty dumb in understanding this, so I'm going to analyse whats going on in detail so I have a better idea of what is being done and why.

I learnt some important lessons from doing this.

  1. If you don't understand a line of code break it down until you do. This will improve your ruby.

  2. irb is your friend, use it and script/console to explore code you don't understand

  3. Even though it takes time, exploring code is far more productive than skipping over it.

To start with I'll have to analyse various ruby statements in some detail. The first is from visitor.rb

require File.join(File.dirname(__FILE__).gsub(/stories(.*)/,"stories"),"helper")
  • require :loads a library, takes a path and tries to load whatever is there.

  • File : abstracts a file object - can be file, dir, symlink.

  • File.join :takes a bunch of strings and joins them together using the default file seperator (File::SEPARATOR)

From the above we can see that it looks like we are going to join a couple of strings together and that the result will end in helper

  • __FILE__ :name of file containing current code being executed. This will be visitor.rb

  • File.dirname(filename) gives the directory containing the file.

  • File.dirname(__FILE__) this gives the directory of the file containing the code being executed. This directory will be dependent on where the code is being executed from. So if we call the file from the directory its in we will get ".". However if we call from the directory above, and the directory the file is in is called 'story' then we will get "story". The return value will be a String

-- gsub(pattern, replacement) :this is a method of String, that returns a copy of the string with all occurences of pattern replaced by replacement

-- gsub(/stories(.*)/,"stories" :this will remove anything that follows stories in the string.

We know can work out a big part of this code


The idea here is that the file this code is in is somewhere in a file hierarchy under a directory called stories. What we want to do is go up to that directory, and we want to do that in a way that is independent of how far down we may be in the hierarchy. The following illustrates this (run in irb)

>> 'stories/stories/ppo'.gsub(/stories(.*)/,"stories")
=> "stories"

Now we can grok the whole line. The join will concatenate '/helper' giving stories/helper. So the line of code will load the code in the file helper which is located in the stories folder somewhere above this file.