Module.new with class_eval

This is a big fix. But I want you to focus on this block of change. http://github.com/rails/rails/commit/d916c62cfc7c59ab6411407a05b946d3dd7535e9#L2L1304

Even without understanding the full context of the code, I cannot think of a scenario in which I would use

include Module.new { class_eval <<-RUBY def foo puts 'foo' end RUBY } 

Then the end result is that in the root context (self immediately before include Module.new ) a method called foo added.

If I pulled out the Module.new code, and if I stay only class_eval , then I will have a method called foo in self .

What am I missing.

+4
source share
2 answers

If you dig in the documentation , you will find that turning on the module will add methods there only if they are not already defined. Thus, this approach will not overwrite the method if it already exists.

+5
source

This ActiveRecord code was asked in another question, where did he get a great answer. fooobar.com/questions/743458 / ...

However, the simplified eval line removes the motivation for writing this code, so it seems confusing. In unaltered code, block binding captures the local variable used to reflect in the association: #{reflection.name}.clear .

0
source

Source: https://habr.com/ru/post/1309481/


All Articles