如何省略方法链的中间部分?
假设我有一个带有 save
方法的类,以及三个使用别名修改它的 mixin,例如
module Callbacks
def save_with_callbacks
callback :before_save
save_without_callbacks
end
end
alias_method_chain :save, :callbacks
end
,与 save_with_transaction
和 save_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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论如何,对我来说,您唯一的选择似乎是提供第二个调用链来进一步处理此功能。我认为你不能用别名来做到这一点;您必须定义一个调用旧方法的新方法,例如:
(顺便说一句,长长的别名链不是会让你的代码非常难以阅读吗?我个人认为我会努力避免它们。)
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:
(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.)