加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 这种弃用方法如何工作?

发布时间:2020-12-16 19:02:13 所属栏目:百科 来源:网络整理
导读:我试图理解这个电话: deprecate :new_record?,:new? 它使用这种弃用方法: 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 #{
我试图理解这个电话:
deprecate :new_record?,:new?

它使用这种弃用方法:

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

我真的不明白这里使用的元编程.但是,这只是另一种别名new_record的方法吗?方法 – 所以实际上,new_record?仍然可用,但在使用时会发出警告?有谁想解释这是如何工作的?

解决方法

好的,所以这里发生的是old_method的所有功能都已由程序员移动到new_method.要使两个名称指向相同的功能但请注意弃用,程序员将放入弃用行.这会导致< -RUBY heredoc( http://en.wikipedia.org/wiki/Heredoc)中指定的字符串在类级别被解释为代码(已评估).字符串插值的工作方式与普通的ruby字符串相同.

然后代码看起来像这样(如果我们要扩展元编程)

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?,&block)
  end
end

我希望这是有道理的

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读