ruby - 如何修补此 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
我希望上述方法可行,但始终失败。我真的很难理解正在发生的事情。
解决方案
我想你可以include Discard::Model
在included
街区
# 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
推荐阅读
- reactjs - 找不到模块:无法解析“react-bootstrap/Media”
- reactjs - Reactjs Rest API 响应解码 JSON
- jquery - Jquery 编辑 css 字体系列值
- java - 如何以最佳方式处理“无法通过子选择加载集合:”
- python - 如果我收到此特定错误,我该如何重试?
- azure - 如何将格式化日期插入 Azure DevOps“经典”发布管道的文件名?
- java - 如何为 RestController 配置 SpringBoot 认证
- arrays - 按时间查询Excel数组
- sql-server - 如何在 SQL Server 中比较和匹配表行时显示负值
- r - 根据来自 3 列的信息进行过滤