2015-04-17 22 views
8

在Ruby中(甚至更多:Rails),它是easy to mark methods as deprecated如何在Ruby中將類標記爲已棄用?

但是,我怎樣才能將整個班級標記爲已棄用?我想提出只要使用一類的警告:

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 - 塊將是堅持這種警告的地方。那是正確的地方嗎?還是有更好的方法?

回答

3

您可以使用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繼續工作,並警告他們使用淘汰類的用戶。

這是迄今爲止我見過的最好的棄用類目的。

+0

在你的例子中,當你剛纔定義了'const_missing'時,怎麼會被解僱呢? – berkes

+0

@berkes第一部分不應該在那裏,錯別字 –

+0

在'const_missing'方法中,PaymentMethod \ n end到底是什麼? – berkes

-2

爲什麼不能做這種方式:

def initialize(*args) 
    warn "DEPRECATION WARNING: ..." 
    super 
end 
+0

作者要展示警告所有類的用法(例如繼承),而不僅僅是創建新的對象。 – hedgesky

8

你可能想看看Deprecate這是Ruby的標準庫的一部分:

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. 
+0

這隻會在對象初始化時引發警告。不是當一個類被用作父類或在嵌套類樹中使用時。或者我錯過了一個重要的細節? – berkes

+0

@berkes您可以使用上面的方法來廢棄'inherited'鉤子(類方法),從而棄用繼承:'class BillingMethod;類「自我; deprecate:inherited,:none,2016,4;結束; end'。繼承BillingMethod現在應該發出棄用警告。 – PSkocik

+0

示例中的代碼是錯誤的。因爲':new'是一個類方法,所以你需要在'class << self'塊中包裝'extend ... deprecate'行。 – berkes

相關問題