how to avoid multiple inclusion of a file

S

suresh

Hi

My program is split up into multiple files, each containing a set of
related class definitions. In the main file, all these files are
included by using require. But how can i avoid multiple inclusion of a
file by mistake.

Is there anything similar to C languages #ifndef .......

thanks
suresh
 
J

Jason Roelofs

As long as the require lines are exactly the same, there's nothing to
worry about.

file1.rb:
require 'lib'

file2.rb:
require 'lib'

This will work fine. You will run into problems if you put relative
paths though:

file1.rb:
require 'lib'

lower/file3.rb:
require '../lib'

This will end up require-ing lib.rb twice, and possibly cause problems.

Either use full paths, or add directories to the $LOAD_PATH to protect
against this.

Jason
 
S

suresh

As long as the require lines are exactly the same, there's nothing to
worry about.

file1.rb:
require 'lib'

file2.rb:
require 'lib'

This will work fine. You will run into problems if you put relative
paths though:

file1.rb:
require 'lib'

lower/file3.rb:
require '../lib'

This will end up require-ing lib.rb twice, and possibly cause problems.

Either use full paths, or add directories to the $LOAD_PATH to protect
against this.

Jason

Hi Jason,

Will tell you what happened to me. I had some database populating code
in some import class definitions. By mistake that file got included
twice and I had to spend a lot of time to figure out how this
happened. So thats why my question, how can I avoid multiple inclusion
of files.

suresh
 
J

Jason Roelofs

Hi Jason,

Will tell you what happened to me. I had some database populating code
in some import class definitions. By mistake that file got included
twice and I had to spend a lot of time to figure out how this
happened. So thats why my question, how can I avoid multiple inclusion
of files.

suresh

I just told you how to avoid it. If you're getting collisions, then
you're doing what I've outlined above.

Jason
 
A

ara.t.howard

Hi Jason,

Will tell you what happened to me. I had some database populating code
in some import class definitions. By mistake that file got included
twice and I had to spend a lot of time to figure out how this
happened. So thats why my question, how can I avoid multiple inclusion
of files.

suresh


if you are writing the files that are included you can self-protect them

unlss defined? $mylib

module MyLib
end

end


however, if you expect something like rails or ramaze to autoload
these files in development mode think twice.

a @ http://codeforpeople.com/
 

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

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top