I was trying to understand this call:
我试图理解这个电话:
deprecate :new_record?, :new?
which uses this deprecate method:
它使用这种弃用方法:
def deprecate(old_method, new_method)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{old_method}(*args, &block)
warn "\#{self.class}##{old_method} is deprecated," +
"use \#{self.class}##{new_method} instead"
send(#{new_method.inspect}, *args, &block)
end
RUBY
end
I don't really understand the metaprogramming that's being used here. But, is this just another way of aliasing the new_record?
method - so in effect, new_record?
is still available but it issues a warning when you use it? Would anyone like to explain how this works?
我真的不明白这里使用的元编程。但是,这只是另一种别名new_record的方法吗?方法 - 所以实际上,new_record?仍然可用,但在使用它时会发出警告?有谁想解释这是如何工作的?
1 个解决方案
#1
10
ok, so what happens here is that all the functionality of old_method has been moved to new_method by the programmer. To make both names point to the same functionality but note the deprecation, the programmer puts in the deprecate
line. This causes the string specified in the <-RUBY heredoc (http://en.wikipedia.org/wiki/Heredoc) to be interpreted as code (evaluated) at the class level. The string interpolations work just as they do in normal ruby strings.
好的,所以这里发生的是old_method的所有功能都已由程序员移动到new_method。要使两个名称指向相同的功能但请注意弃用,程序员将放入弃用行。这会导致<-RUBY heredoc(http://en.wikipedia.org/wiki/Heredoc)中指定的字符串在类级别被解释为代码(已评估)。字符串插值的工作方式与普通的ruby字符串相同。
The code then looks something like this (if we were to expand out the metaprogramming)
然后代码看起来像这样(如果我们要扩展元编程)
class SomeClass
def new?; true; end
deprecate :new_record?, :new? # this generates the following code
def new_record?(*args, &block)
warn "SomeClass#new_record? is deprecated," +
"use SomeClass#new? instead"
send(:new?, *args, &block)
end
end
I hope that makes sense
我希望这是有道理的
#1
10
ok, so what happens here is that all the functionality of old_method has been moved to new_method by the programmer. To make both names point to the same functionality but note the deprecation, the programmer puts in the deprecate
line. This causes the string specified in the <-RUBY heredoc (http://en.wikipedia.org/wiki/Heredoc) to be interpreted as code (evaluated) at the class level. The string interpolations work just as they do in normal ruby strings.
好的,所以这里发生的是old_method的所有功能都已由程序员移动到new_method。要使两个名称指向相同的功能但请注意弃用,程序员将放入弃用行。这会导致<-RUBY heredoc(http://en.wikipedia.org/wiki/Heredoc)中指定的字符串在类级别被解释为代码(已评估)。字符串插值的工作方式与普通的ruby字符串相同。
The code then looks something like this (if we were to expand out the metaprogramming)
然后代码看起来像这样(如果我们要扩展元编程)
class SomeClass
def new?; true; end
deprecate :new_record?, :new? # this generates the following code
def new_record?(*args, &block)
warn "SomeClass#new_record? is deprecated," +
"use SomeClass#new? instead"
send(:new?, *args, &block)
end
end
I hope that makes sense
我希望这是有道理的