如何省略方法链的中间部分?

发布于 2024-11-18 08:55:05 字数 747 浏览 7 评论 0原文

假设我有一个带有 save 方法的类,以及三个使用别名修改它的 mixin,例如

module Callbacks
  def save_with_callbacks
    callback :before_save
    save_without_callbacks
    end
  end

  alias_method_chain :save, :callbacks
end

,与 save_with_transactionsave_with_timestamps 类似,混合在按照这个顺序,所以 MyModel#save 调用 save_with_timestamps,后者又调用 save_with_transaction,后者又调用save_with_callbacks,最终调用原始save

现在假设我想在没有交易的情况下保存。我可以调用 save_without_transaction,但这不会调用代码来设置时间戳。

如何使用时间戳和回调保存模型,但不保存事务?

我可以重新排序 mixins,但我的问题是省略中间部分,而不是具体的事务。如何省略方法链的中间部分?

注意 - 为了简洁起见,我使用了 RoR 的 alias_method_chain,但我的问题一般适用于 ruby

Suppose I have a class with a save method, and three mixins which modify it using aliasing, e.g.

module Callbacks
  def save_with_callbacks
    callback :before_save
    save_without_callbacks
    end
  end

  alias_method_chain :save, :callbacks
end

and similarly for save_with_transaction and save_with_timestamps, mixed in in that order, so MyModel#save calls save_with_timestamps, which calls save_with_transaction, which calls save_with_callbacks, which finally calls the original save.

Now suppose I want to save without a transaction. I can call save_without_transaction, but that doesn't call the code to set the timestamps.

How can I save my model with timestamps and callbacks, but no transaction?

I could reorder the mixins, but my question is about omitting the middle, rather than specifically transactions. How can I omit the middle of a chain of methods?

NOTE - I've used RoR's alias_method_chain for brevity, but my question applies to ruby in general

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

审判长 2024-11-25 08:55:05

无论如何,对我来说,您唯一的选择似乎是提供第二个调用链来进一步处理此功能。我认为你不能用别名来做到这一点;您必须定义一个调用旧方法的新方法,例如:

  1. MyModel#save <-save_with_timestamps <- save_with_transaction <- save_with_callbacks <-save。
  2. MyModel#save_other <-save_with_timestamps_other <- save_with_callbacks_other <-save_other。

(顺便说一句,长长的别名链不是会让你的代码非常难以阅读吗?我个人认为我会努力避免它们。)

Your only option seems to be -- to me, anyway -- to provide a second calling chain that handles this functionality further up. I don't think you can do this with aliasing; you're going to have to define a new method that calls the old method, instead - so something like:

  1. MyModel#save <-save_with_timestamps <- save_with_transaction <- save_with_callbacks <-save.
  2. MyModel#save_other <-save_with_timestamps_other <- save_with_callbacks_other <-save_other.

(As an aside, aren't long chains of aliases going to make your code very difficult to read? Personally I think I would work hard to avoid them.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文