如何在Ruby中将类标记为已弃用?
在Ruby中(甚至更多:Rails)就是这样 但是如何将整个类标记为已弃用?每当使用类时,我都要发出警告:如何在Ruby中将类标记为已弃用?,ruby,deprecation-warning,Ruby,Deprecation Warning,在Ruby中(甚至更多:Rails)就是这样 但是如何将整个类标记为已弃用?每当使用类时,我都要发出警告: class BillingMethod end BillingMethod.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead. 或者在继承中使用时: class Sofort < BillingMethod end Sofort.new
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-Sofort弃用警告:类BillingMethod已弃用。改用PaymentMethod。
或者,在嵌套类中使用时:
class BillingMethod::Sofort < BillingMethod
end
BillingMethod::Sofort.new #=> DEPRECATION WARNING: the class BillingMethod is deprecated. Use PaymentMethod instead.
class BillingMethod::Sofort弃用警告:类BillingMethod已弃用。改用PaymentMethod。
我认为a区应该是张贴这种警告的地方。那是正确的地方吗?或者有更好的方法吗?为什么不这样做:
def initialize(*args)
warn "DEPRECATION WARNING: ..."
super
end
您可以使用来弃用常量,并通过扩展弃用类
引用未定义的常量时,将调用
常量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
的现有代码继续工作,并警告用户使用不推荐的类
这是迄今为止我见过的最好的一个用于弃用类的工具。您可能想看看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
作者希望在所有类用法(例如继承)上显示警告,而不仅仅是创建新对象。在您的示例中,当您刚刚定义了
const_missing
时,如何激发它?@berkes第一部分不应该在那里,键入const_missing
方法,PaymentMethod\n end
到底实现了什么?const_missing
在引用模块中未定义的常量时被调用。它返回一个用于该常量的值(PaymentMethod,在本例中为),在我看来,在关闭const\u missing
-方法之前的最后一个end
是超级错误的。在Ruby 2.1.x中,它给出了一个语法错误。只有在初始化对象时才会发出警告。当类用作父类或在嵌套类树中使用时,则不适用。还是我遗漏了一个重要的细节?@berkes您可以使用上面的内容来弃用继承的
钩子(类方法),从而弃用继承:类BillingMethod;类示例中的代码是错误的。因为:new
是一个类方法,所以需要将extend…deprecate
行包装在class@berkes中,我修复了我的示例。
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.