首页 > 解决方案 > 如何修补此 Ruby 模块以避免代码重复?

问题描述

我想修改我在 Rails 中使用的模块。目前,我正在包含该模块,然后还修补了它的一些功能:


class Task < ApplicationRecord
  include Discard::Model
  self.discard_column = :deleted_at

  # patching the module's .discard method to allow for discarded_at to be a variable
  def discard(discarded_at = DateTime.now)
    return false if discarded?
    run_callbacks(:discard) do
      update_attribute(self.class.discard_column, discarded_at)
    end
  end
end

作为参考,可以在此处查看原始.discard方法。

如何将此补丁抽象为可重用的超级模块?

为了避免重复此代码,我希望能够将我的补丁提取到原始模块的新版本中并使用它而不是原始模块。

我想要什么:

# task.rb
class Task < ApplicationRecord
  include SuperDiscard
end
# super_discard.rb
module SuperDiscard 
  extend Discard::Model

  # NB While this hints at what I want it definitely doesn't work :(
  include Discard::Model
   def discard(discarded_at = DateTime.now)
    return false if discarded?
    run_callbacks(:discard) do
      update_attribute(self.class.discard_column, discarded_at)
    end
  end

  included do 
    self.discard_column = :deleted_at
  end
end

我希望上述方法可行,但始终失败。我真的很难理解正在发生的事情。

标签: ruby

解决方案


我想你可以include Discard::Modelincluded街区

# super_discard.rb
module SuperDiscard
 extend ActiveSupport::Concern

 included do
  include Discard::Model
  self.discard_column = :deleted_at
  def discard(discarded_at = DateTime.now)
    return false if discarded?
    run_callbacks(:discard) do
      update_attribute(self.class.discard_column, discarded_at)
    end
  end
 end
end

# task.rb
class Task < ApplicationRecord
  include SuperDiscard
end

推荐阅读