如何在Ruby中将类标记为Deprecated?

Ruby中(甚至更多:Rails)它是 easy to mark methods as deprecated.

但是如何将整个类标记为已弃用?我想在使用类时发出警告:

class BillingMethod
end

BillingMethod.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.

或者在继承中使用它时:

class Sofort < BillingMethod
end

Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.

或者,在嵌套类中使用时:

class BillingMethod::Sofort < BillingMethod
end

BillingMethod::Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.

我认为class_eval区块将成为发出此类警告的地方.那是正确的地方吗?还是有更好的方法

解决方法

您可以使用 const_missing来弃用常量,并通过扩展来使用类.

当引用未定义的常量时,将调用const_missing.

module MyModule

  class PaymentMethod
    # ...
  end

  def self.const_missing(const_name)
    super unless const_name == :BillingMethod
    warn "DEPRECATION WARNING: the class MyModule::BillingMethod is deprecated. Use MyModule::PaymentMethod instead."
    PaymentMethod
  end
end

这允许引用MyModule :: BillingMethod的现有代码继续工作,并警告用户他们使用已弃用的类.

这是我迄今为止看到的最令人贬低的课程目的.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...