Loads and executes the Ruby program in the file _filename_. If the
filename does not resolve to an absolute path, the file is
searched
for in the library directories listed in +$:+. If the optional wrap parameter is +true+, the loaded script will be executed
under an anonymous module, protecting the calling program’s global
namespace. In no circumstance will any local variables in the
loaded file be propagated to the loading environment.
Load is more conventional but eval is more flexible (source can be
modifyed before evaluated).
Are there any hidden gotchas?
by
TheR
Yes, there IS a difference, and yes, there ARE gotchas.
The load way:
module Alpha
load ‘file.rb’
end
class Beta
load ‘file.rb’
end
class Gamma
include Alpha
end
The eval way:
module Alpha
c = File.open(‘file.rb’) {|f| f.read }
eval c
end
class Beta
c = File.open(‘file.rb’) {|f| f.read }
eval c
end
class Gamma
include Alpha
end
In 1., the contents of file.rb are loaded in global namespace. But
that’s not the whole story. When file.rb defines a method my_method,
you’ll end up with four methods: a public main#my_method, a private
Alpha#my_method, a private Beta#my_method and a private Gamma#my_method.
Not quite a “least surprise”.
2.'s behaviour is more intuitive. You’ll get a public Alpha#my_method, a
public Beta#my_method and a public Gamma#my_method. But if file.rb has
any load (or require) of its own, that stuff will be loaded in your
script’s global namespace…
And there’s my problem. I’m using two different libraries both
containing (directly or indirectly) modules or classes with the same
name. To avoid name conflicts, I would like my script to wrap them (or
at least one of them) in their own namespace. But such a thing seems to
be impossible if those modules/classes are placed far away in a long
chain of required libraries. Is there any way out of this library hell?
…
And there’s my problem. I’m using two different libraries both
containing (directly or indirectly) modules or classes with the same
name. To avoid name conflicts, I would like my script to wrap them (or
at least one of them) in their own namespace. But such a thing seems to
be impossible if those modules/classes are placed far away in a long
chain of required libraries. Is there any way out of this library hell?
Found this one in another thread:
Moreover, there is already brilliant Script[1] library, which allows to
do such kind of things right now.