# Require just in a context?

**URL:** <https://www.ruby-forum.com/t/require-just-in-a-context/54389>\
**Category:** Ruby\
**Created:** [March 3, 2006, 4:16am UTC](https://www.ruby-forum.com/t/require-just-in-a-context/54389 "2006-03-03T04:16:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cap](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e9bcb4/32.png) [@cap](https://www.ruby-forum.com/u/cap)\
**Post date:** [March 3, 2006, 4:16am UTC](https://www.ruby-forum.com/t/require-just-in-a-context/54389/1 "2006-03-03T04:16:18Z")

</div>

Can I make some libraray just work in a context ?

I add a new ruby file into my app using “require ‘mathn’” but i don’t  
want every ruby file to use the ‘mathn’, how can I do it?

---

<div class="post-metadata">

**Author:** ![cap](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e9bcb4/32.png) [@cap](https://www.ruby-forum.com/u/cap)\
**Post date:** [March 4, 2006, 1:44am UTC](https://www.ruby-forum.com/t/require-just-in-a-context/54389/2 "2006-03-04T01:44:38Z")

</div>

E. Saynatkari wrote:

> (see the docs) or a library such as Script (see RAA) which  
> uses a named module. This approach might not work with mathn  
> or anything else that modifies existing classes.

Nope. If you Kernel#load or Module#module\_eval a file which requires  
mathn, the effect will still be global.

$ ruby -e ‘load “foo.rb”; p 1/2’  
1/2  
$ ruby -e ‘m=Module.new; m.module\_eval(File.read(“foo.rb”)); p 1/2’  
1/2  
$ ruby -v  
ruby 1.8.4 (2005-12-24) [i686-linux]

I think what you want is something called behaviors. See the list  
archives…

---

<div class="post-metadata">

**Author:** ![cap](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/e9bcb4/32.png) [@cap](https://www.ruby-forum.com/u/cap)\
**Post date:** [March 3, 2006, 8:02pm UTC](https://www.ruby-forum.com/t/require-just-in-a-context/54389/3 "2006-03-03T20:02:14Z")

</div>

cap wrote:

> Can I make some libraray just work in a context ?
> 
> I add a new ruby file into my app using “require ‘mathn’” but i don’t  
> want every ruby file to use the ‘mathn’, how can I do it?

Well, anytime you call #require, the effect will be global.  
You can delay the call until a certain point in your program  
(possibly useful if there is a possibility that it would not  
be loaded at all) since #require is just a method. For example,

def foobar(x, y)  
require ‘mathn’  
# …  
end

Would be fine (but would still have an effect just like if  
you did it at the top of the file).

As an alternative, you could wrap the loaded file into a  
module either using #load which can use an anonymous module  
(see the docs) or a library such as Script (see RAA) which  
uses a named module. This approach might not work with mathn  
or anything else that modifies existing classes.

E
