[MacRuby-devel] require [was: [ANN] The Flying Camera (game)]

russell muetzelfeldt russm-macruby-devel at slofith.org
Sat Dec 18 13:58:01 PST 2010


> Date: Fri, 17 Dec 2010 11:13:35 -0800
> From: Gabriel Gilder <gabriel at gabrielgilder.com>
> 
> I ended up solving this problem in my MacRuby app by writing a little class
> to load dependencies - it keeps track of the full file paths of every
> dependency in a class variable and makes sure to only load a file once even
> if you request it again. Let me know if you would like me to post some
> sample code...

This is just reinventing Ruby's $" builtin variable - require stores the name of files you require in here and doesn't load them if they've been loaded already.

If that's not working for you and you're getting errors with library files being loaded multiple times, you should check that $: (aka $LOAD_PATH) is set correctly and you're not requiring files with relative pathnames. The names stored in $" aren't normalised, they're exactly what you passed to require, so if you have a file hierarchy like

main.rb
lib/
 | foo.rb
 | bar.rb
 \ baz/
    \ asd.rb

where main.rb includes

require './lib/baz/asd'
require './lib/bar'

and asd.rb has

require '../bar'

then bar will be included twice since '../bar' does not match './lib/bar'. what you should do is add the lib directory to $: and then change the require lines in main.rb to

require 'baz/asd'
require 'bar'

and in asd.rb to

require 'bar'

so that the normal mechanism that require uses to only load files once can actually work as designed. If for some reason this is impossible, you could also change all your require lines from

require '../bar'

to

require File.expand_path('../bar')

which should expand everything out to absolute paths so that (once again) the path matching in require can work as designed.


cheers

Russell



More information about the MacRuby-devel mailing list