# Requiring the same file and capturing the constants

**URL:** <https://www.ruby-forum.com/t/requiring-the-same-file-and-capturing-the-constants/137500>\
**Category:** Ruby\
**Created:** [May 13, 2008, 6:19pm UTC](https://www.ruby-forum.com/t/requiring-the-same-file-and-capturing-the-constants/137500 "2008-05-13T18:19:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dorelal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/3da27b/32.png) [@dorelal](https://www.ruby-forum.com/u/dorelal)\
**Post date:** [May 13, 2008, 6:19pm UTC](https://www.ruby-forum.com/t/requiring-the-same-file-and-capturing-the-constants/137500/1 "2008-05-13T18:19:44Z")

</div>

## file1.txt

class Person  
end  
module Speak  
end

The task is to printout all the constants listed in the file. In this  
case there are Person and Speak.

I need to handle two cases.

1. The system loads the file for the first time. I guess in this case I  
can use ObjectSpace.each\_object or ObjectSpace.some\_method from API to  
get before and after picture. Subtract the before picture and I will get  
the constants.

2. The second case is when file1.txt is already loaded into the  
application. So in this case I can’t do before and after thing. How can  
I get constants in this case without before and after picture.

Thanks

---

<div class="post-metadata">

**Author:** ![dorelal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/3da27b/32.png) [@dorelal](https://www.ruby-forum.com/u/dorelal)\
**Post date:** [May 13, 2008, 6:54pm UTC](https://www.ruby-forum.com/t/requiring-the-same-file-and-capturing-the-constants/137500/2 "2008-05-13T18:54:22Z")

</div>

Raj S. wrote:

> Thanks  
> If you have control over _how_ the file is loaded, you can do this,  
> using [http://redshift.sourceforge.net/script:](http://redshift.sourceforge.net/script:)

[~/tmp] cat file.rb  
class Person  
end  
module Speak  
end  
[~/tmp] cat main.rb  
require ‘script’  
mod = Script.load ‘file.rb’  
p mod.constants  
[~/tmp] ruby main.rb  
[“Person”, “Speak”]

The trick is really just reading the file, creating a module, and  
calling module\_eval on that with the contents of the file.
