【问题标题】:The best way to deprecate all class methods in Rails在 Rails 中弃用所有类方法的最佳方法
【发布时间】:2021-02-16 17:01:46
【问题描述】:

我有一个具有多个类方法的类(它不是ActiveRecord 模型)。必须弃用所有类方法。最好的方法是什么?

class MyClass
  class << self
    def method_to_deprecate_1
      ...
    end
    ...
    def method_to_deprecate_100
      ...
    end
  end
end

【问题讨论】:

  • 只需将Kernel.warn(或类似的东西)插入每个受影响的方法体。
  • @SergioTulentsev 这就是我想要避免的。方法太多了。寻找单班轮。
  • 即使有 100 种方法,这也是 30 分钟的工作时间。并且您准确地标记了要弃用的方法。不多也不少。在我的书中,这比影响未知/可变数量方法的 MP 要好。
  • @MaksymPolshcha 刚刚更新了我的原始答案以满足您的需求,希望对您有所帮助

标签: ruby-on-rails ruby deprecated class-method deprecation-warning


【解决方案1】:

Ruby 有一个特殊的模块 Gem::Deprecate 用于此,这是官方文档中的一个示例:

class Legacy
  def self.klass_method
    # ...
  end

  def instance_method
    # ...
  end

  extend Gem::Deprecate
  deprecate :instance_method, "X.z", 2011, 4

  class << self
    extend Gem::Deprecate
    deprecate :klass_method, :none, 2011, 4
  end
end

这将导致:

2.5.0 :020 > Legacy.new.instance_method
NOTE: Legacy#instance_method is deprecated; use X.z instead. It will be removed on or after 2011-04-01.
Legacy#instance_method called from (irb):20.
 => nil 
2.5.0 :021 > Legacy.klass_method
NOTE: Legacy.klass_method is deprecated with no replacement. It will be removed on or after 2011-04-01.
Legacy.klass_method called from (irb):21.
 => nil

编辑: 要直接回答您的问题,这是我能想到的最优雅的方式来弃用所有类方法:

class Kek
   class << self
     def old_method_1
       # ...
     end

     def old_method_2
       # ...
     end

     extend Gem::Deprecate

     # instance methods here are our actual class methods + all of the Object's methods from Ruby
     instance_methods(false).each { |method_to_deprecate| deprecate(method_to_deprecate, :none, 2011, 4) }
   end
end

【讨论】:

  • instance_methods(false).each { |method_to_deprecate|...} 怎么样,但不应该在创建类后完成(Kek.methods(false).each { 'method_to_deprecate|...}?在创建类后调用Kek.extend Gem::Deprecate 也可能更干净。跨度>
  • 谢谢你,@CarySwoveland!我用instance_methods(false) 编辑了我的答案。不知道这是可能的,在 Ruby 中总是有一个更简单的解决方案 :) 关于在创建类后弃用...deprecate 是一个私有方法,在类创建后不可用。即使不是这样,这意味着据我所知,每次在新文件中使用 Kek 类时都需要弃用这些方法。
  • 不应该extend Gem::Deprecateinclude Gem::Deprecate,因为它在class &lt;&lt; self ... end 之内?更好的是,imo 是在单例类构造之外的extend Gem::Deprecate。我相信instance_methods(false).each { ...} 也应该在外面,尽管我仍然同意我在第一条评论中给出的意见。
  • 回复您的评论:鉴于 Kek 的类方法已被弃用,建议将 Kek 放在需要的单独模块中,在这种情况下,该模块还可以包含Kek.extend Gem::Deprecate; Kek.methods(false).each { |method_to_deprecate| Kek.send(method_to_deprecate, ...) }.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
  • 2012-02-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多