9

在 Ruby(甚至更多:Rails)中,很容易将方法标记为 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-block 将是粘贴此类警告的地方。那是正确的地方吗?还是有更好的方法?

4

3 回答 3

11

您可能想看看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

使用该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.
于 2015-04-17T11:05:37.843 回答
5

您可以使用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继续工作,并警告用户他们使用已弃用的类。

这是迄今为止我所见过的最好的用于贬低班级的目的。

于 2015-04-17T10:09:08.913 回答
-2

为什么不这样做:

def initialize(*args)
  warn "DEPRECATION WARNING: ..."
  super
end
于 2015-04-17T10:04:29.507 回答