Module.new with class_eval
This is a large commit. But I want you to concentrate on this change block. http://github.com/rails/rails/commit/d916c62cfc7c59ab6411407a05b946d3dd7535e9#L2L1304
Even without understanding the full context of the code I am not able to think of a scenario where I would use
include Module.new {
class_eval <<-RUBY
def foo
puts 'foo'
end
RUBY
}
Then end result is that in the root context (self just before include Module.new
) a method called foo
has been added.
If I take out the Module.new
code and if I only leave class_eval
in that case also I will have a method called foo
in self
.
W开发者_运维知识库hat am I missing.
If you dig in the documentation you find that including a module will add the methods therein only if they are not already defined. So this approach will not overwrite the method in case it is already there.
This ActiveRecord code has been asked about in another question, where it received an excellent answer. https://stackoverflow.com/a/3473479/420947
However, the simplified eval string here removes the motivation to write this code, which is why it appears confusing. In the unchanged code, the block binding captures a local variable used to reflect on the association: #{reflection.name}.clear
.
精彩评论