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

前端之家收集整理的这篇文章主要介绍了如何在Ruby中将类标记为Deprecated?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Ruby中(甚至更多:Rails)它是 easy to mark methods as deprecated.

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

  1. class BillingMethod
  2. end
  3.  
  4. BillingMethod.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.

或者在继承中使用它时:

  1. class Sofort < BillingMethod
  2. end
  3.  
  4. Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.

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

  1. class BillingMethod::Sofort < BillingMethod
  2. end
  3.  
  4. BillingMethod::Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.

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

解决方法

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

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

  1. module MyModule
  2.  
  3. class PaymentMethod
  4. # ...
  5. end
  6.  
  7. def self.const_missing(const_name)
  8. super unless const_name == :BillingMethod
  9. warn "DEPRECATION WARNING: the class MyModule::BillingMethod is deprecated. Use MyModule::PaymentMethod instead."
  10. PaymentMethod
  11. end
  12. end

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

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

猜你在找的Ruby相关文章