Sunday, November 20, 2011

Breaking the example down

The classic example:


Let's start at the first line - (require 'sinatra') - what does this actually do?
After a quick lookup the require keyword will take the string you give it, which must be a path to a file e.g. './childDir/blah.rb' or a shortened name 'blah'.

Let's experiment for a second...
/*Create a test file (to test the require)... */
mkdir experiments
cd experiments/
vi require_experiment.rb
i /*for insert*/
require './test/hello.rb'
ESC
:wq

mkdir test
vi test/hello.rb
i
puts 'hello world'
ESC
:wq

Now run the file with ruby require_experiment.rb
and we get:
>> hello world

OK... so now we know that when we require something it runs the code in it.

How about if we leave off '.rb' in the require?
we get:
>> hello world

what if we reference a class from the parent file, and then try to use it in another referenced file??? will that work?






OK... so I get an error:
:29:in `require': no such file to load -- file_with_hello_class (LoadError)

OK... so that's interesting - we can't just reference the file with a name, we need to put "require './file_with_hello_class'" in order for ruby to find it.

Once we correct the require statement - it actually runs!:
>> hello

So... even though we've loaded file_with_hello_class from require_experiment, the hello file can now see the class that was declared in file_with_hello_class.

Another thing we can check is what happens if we run the file from another directory?
cd ..
ruby experiment/require_experiment.rb
>> `require': no such file to load -- ./file_with_hello_class (LoadError)

So the way we've got things setup now... we can't just run the file from anywhere.


What happens if we do a require with a short name e.g. "require 'sinatra'"... well after looking it up, it appears that ruby will look in the directories stored in the global $LOAD_PATH variable for the mentioned file.

Put a 'puts $LOAD_PATH' in your ruby file, run it and try it out OR try it from irb.

There's a problems we came up against with require, where it didn't find a relative file unless we put './' in front of it, and also when we then moved to a parent directory and tried running the file it didn't work. I'll take a look at this in the next post...

No comments:

Post a Comment