module_eval and scope question

R

Ronny

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
 

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

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top