在
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的现有代码继续工作,并警告用户他们使用已弃用的类.
这是我迄今为止看到的最令人贬低的课程目的.