ber*_*kes 9 ruby deprecation-warning
在Ruby中(甚至更多:Rails),很容易将方法标记为已弃用.
但是,如何将整个类标记为已弃用?我想在使用类时发出警告:
class BillingMethod
end
BillingMethod.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.
Run Code Online (Sandbox Code Playgroud)
或者当它在继承中使用时:
class Sofort < BillingMethod
end
Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.
Run Code Online (Sandbox Code Playgroud)
或者,在嵌套类中使用时:
class BillingMethod::Sofort < BillingMethod
end
BillingMethod::Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.
Run Code Online (Sandbox Code Playgroud)
我认为a- class_evalblock将成为发出这种警告的地方.这是正确的地方吗?还是有更好的方法?
您可能想看看Deprecate哪个是Ruby标准库的一部分:
require 'rubygems'
class BillingMethod
extend Gem::Deprecate
class << self
deprecate :new, "PaymentMethod.new", 2016, 4
end
# Will be removed April 2016, use `PaymentMethod.new` instead
def initialize
#...
end
end
Run Code Online (Sandbox Code Playgroud)
使用该deprecated方法会产生如下警告:
BillingMethod.new
# => NOTE: BillingMethod#new is deprecated; use PaymentMethod.new instead. It will be removed on or after 2016-04-01.
# => BillingMethod#new called from file_name.rb:32.
Run Code Online (Sandbox Code Playgroud)
您可以使用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
Run Code Online (Sandbox Code Playgroud)
这允许引用的现有代码MyModule::BillingMethod继续工作,并警告用户他们使用已弃用的类。
这是迄今为止我所见过的最好的弃用类目的。
| 归档时间: |
|
| 查看次数: |
2261 次 |
| 最近记录: |