Using 'require' with modules in the same folder

  • Thread starter Fernando Cacciola
  • Start date
F

Fernando Cacciola

Hi people,

I've modularized my very first ruby program (a port of a bash script).

However, if I use 'load' and the target program is loaded multiple times
(indirectly), I get warnings about redefinition of constants, etc
(understandably)

But if I try to use 'require', it searches for the program in the ruby
distribution. Is there a way to specify within the top level script itself
where to search?

TIA
 
M

mortee

Fernando said:
Hi people,

I've modularized my very first ruby program (a port of a bash script).

However, if I use 'load' and the target program is loaded multiple times
(indirectly), I get warnings about redefinition of constants, etc
(understandably)

But if I try to use 'require', it searches for the program in the ruby
distribution. Is there a way to specify within the top level script
itself where to search?

You can use relative/absolute paths with require. Combined with
__FILE__, more precisely File.dirname(__FILE__), you can require other
files relative to your current one.

mortee
 
F

Fernando Cacciola

Fernando said:
But if I try to use 'require', it searches for the program in the ruby
distribution.
Never mind... the current folder is included in the search path, I just got
confused by an error message from the loaded program.
Is there a way to specify within the top level script
itself where to search?
FWIW

$: << "additional_path"

seems to do it, according to "Programming ruby"
 
X

Xavier Noria

Hi people,

I've modularized my very first ruby program (a port of a bash script).

However, if I use 'load' and the target program is loaded multiple
times (indirectly), I get warnings about redefinition of constants,
etc (understandably)

But if I try to use 'require', it searches for the program in the
ruby distribution. Is there a way to specify within the top level
script itself where to search?

Yes, there's a standard idiom for that:

$:.unshift(File.dirname(__FILE__))

which means: prepend to the list of directories where libraries are
searched ($:) the directory where this file lives. Note that does not
assume the directory is the current working directory, since __FILE__
points to the containing file, no matter how is being evaled.

-- fxn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top