Say I have script A and it executes a ‘require’ for module B and
module C.
Now lets say that within module B there is also a require for module
C that
executes.Do I now have two copies of module C loaded in two seperate
namespaces? Or
is there no harm in this and pretty much the norm?
require checks the filename, and skips if the file already is loaded.
namespace doesn’t have impact on require.
A few other interesting points:
-
the ‘require’ statement (like everything else in ruby) has a return
value. The first time a file is required, the return value is true.
Subsequent calls return false. E.g.:
irb(main):001:0> require ‘date’
=> true
irb(main):002:0> require ‘date’
=> false -
Not sure if ‘namespace’ is the correct term here. Ruby will load the
file (i.e. execute it). Everything defined in the file will be added in
the name space it’s defined in. If the file contains a plain method
definition, it’ll go to class Object; If the file defines a class, a
Class object will be created; If there’s a moule definition, it’ll
create a new module. Stuff inside that module is in it’s own namespace,
and can be 'include’d in the main space. E.g.:
irb(main):001:0> Wx
NameError: uninitialized constant Wx
from (irb):1
irb(main):002:0> StaticBitmap
NameError: uninitialized constant StaticBitmap
from (irb):2
irb(main):003:0> require ‘wxruby’
=> true
irb(main):004:0> Wx
=> Wx
irb(main):005:0> Wx.class
=> Module
irb(main):006:0> StaticBitmap
NameError: uninitialized constant StaticBitmap
from (irb):6
irb(main):007:0> include Wx
=> Object
irb(main):008:0> StaticBitmap.class
=> Class
- If you want to force ruby to reload a file, call ‘load’. E.g.:
t.rb contains the single line: puts “t loaded”
irb(main):001:0> require ‘t’
t loaded
=> true
irb(main):002:0> require ‘t’
=> false
irb(main):003:0> load ‘t’
LoadError: No such file to load – t
from (irb):3:in `load’
from (irb):3
irb(main):004:0> load ‘t.rb’
t loaded
=> true
irb(main):005:0> load ‘t.rb’
t loaded
=> true
irb(main):006:0> require ‘t’
=> false