# Module\_eval and scope question

**URL:** <https://www.ruby-forum.com/t/module-eval-and-scope-question/125504>\
**Category:** Ruby\
**Created:** [January 9, 2008, 7:17pm UTC](https://www.ruby-forum.com/t/module-eval-and-scope-question/125504 "2008-01-09T19:17:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ronny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/94ad74/32.png) [@ronny](https://www.ruby-forum.com/u/ronny)\
**Post date:** [January 9, 2008, 7:17pm UTC](https://www.ruby-forum.com/t/module-eval-and-scope-question/125504/1 "2008-01-09T19:17:35Z")

</div>

When trying to understand a piece of code from the Ruby-On-Rails  
framework,  
I found that I’m still lacking knowledge about scope issues in Ruby.  
Here is a  
stripped down version of the code I’m trying to understand (in case  
you  
happen to use Rails: This is from file scaffolding.rb):

module ActionController  
module Scaffolding  
…  
module ClassMethods  
def scaffold(model\_id, options = {})  
…  
unless options[:suffix]  
module\_eval \<\<-“end\_eval”, **FILE** , **LINE**  
def index  
list  
end  
end\_eval  
end  
…  
end  
end  
end

The purpose of this code is to create at run-time the function  
‘index’.  
My question is: Why do I need ‘module\_eval’ here? I understand that  
I can use module\_eval to evaluate an expression in the context of  
a different class/module, for example

mymodule.module\_eval \<\<“END”  
def foo  
end  
END

would define foo in the context of mymodule. In the example code  
above,  
however, there is no SOMETHING.module\_eval defined, so the scope  
would be ClassMethods anyway and, so I had thought, the author could  
have written simply:

module ActionController  
module Scaffolding  
…  
module ClassMethods  
def scaffold(model\_id, options = {})  
…  
unless options[:suffix]  
def index  
list  
end  
end  
…  
end  
end  
end

Of course I’m pretty sure that there was some purpose in using  
module\_eval  
here, though. Could anybody enlighten me why it is necessary, and why  
my  
simpler solution would not work?

Ronald

---

<div class="post-metadata">

**Author:** ![ronny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/94ad74/32.png) [@ronny](https://www.ruby-forum.com/u/ronny)\
**Post date:** [January 9, 2008, 7:29pm UTC](https://www.ruby-forum.com/t/module-eval-and-scope-question/125504/2 "2008-01-09T19:29:59Z")

</div>

I believe the answer is that it’s evaluated at run-time, so the  
module\_eval refers to a different module, but I’m not sure about that.  
It could just be that the Rails guys screwed up or something.

–  
Giles B.

Podcast: [http://hollywoodgrit.blogspot.com](http://hollywoodgrit.blogspot.com)  
Blog: [http://gilesbowkett.blogspot.com](http://gilesbowkett.blogspot.com)  
Portfolio: [http://www.gilesgoatboy.org](http://www.gilesgoatboy.org)  
Tumblelog: [http://giles.tumblr.com](http://giles.tumblr.com)
