# Load/require into module/class, revisted

**URL:** <https://www.ruby-forum.com/t/load-require-into-module-class-revisted/79688>\
**Category:** Ruby\
**Created:** [December 18, 2006, 7:32am UTC](https://www.ruby-forum.com/t/load-require-into-module-class-revisted/79688 "2006-12-18T07:32:24Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Trans](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/dfb087/32.png) [@Trans](https://www.ruby-forum.com/u/Trans)\
**Post date:** [December 18, 2006, 7:32am UTC](https://www.ruby-forum.com/t/load-require-into-module-class-revisted/79688/1 "2006-12-18T07:32:24Z")

</div>

revisting a topic brought up a few times before. a good reference  
being:

[http://groups.google.com/group/comp.lang.ruby/browse\_thread/thread/74f323436b2bc85f/0c7780b698866cc5?lnk=gst&q=load+import&rnum=4&hl=en#0c7780b698866cc5](http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/74f323436b2bc85f/0c7780b698866cc5?lnk=gst&q=load+import&rnum=4&hl=en#0c7780b698866cc5)

after considerable thought i think the interface that makes the most  
sense is #module\_load / #module\_require. below is an implementation  
please suggest improvements to the code.

thanks,  
t.

* * *

module Module

# Load file into module/class namespace.

def module\_load( path )  
if path =~ /^[/~.]/  
file = File.expand\_path(path)  
else  
$LOAD\_PATH.each do |lp|  
file = File.join(lp,path)  
break if File.exist?(file)  
file = nil  
end  
end

```
module_eval(File.read(file))

```

end

# Require file into module/class namespace.

def module\_require( path )  
if path =~ /^[/~.]/  
file = File.expand\_path(path)  
else  
$LOAD\_PATH.each do |lp|  
file = File.join(lp,path)  
break if File.exist?(file)  
file += ‘.rb’  
break if File.exist?(file)  
file = nil  
end  
end

```
@loaded ||= {}
if @loaded.key?(file)
  false
else
  @loaded[file] = true
  module_eval(File.read(file))
  true
end

```

end

end

class Class  
alias class\_load module\_load  
alias class\_require module\_require  
end
