gpt4 book ai didi

ruby-on-rails - 检查 mixee 类上是否定义了方法?

转载 作者:数据小太阳 更新时间:2023-10-29 09:03:41 24 4
gpt4 key购买 nike

我们有一个模块来处理取消模型。它很干净,工作很好,但是我们遇到了一个问题,我们想要将它混合到一个已经定义了我们的模块方法(cancel! 等)的类中。

我们试图想出新的名字来避免冲突,但一切似乎都不太理想,我们喜欢调用 cancel! 的干净利落。因此,我们决定要执行以下操作:

def cancel!
cancelly_stuff
if class.parent.respond_to(:cancel!) super
end

但是,它是一个模块,所以我们将它混合到的类不是 class.parent。我无法用谷歌搜索如何引用模块的 mixee 类。

最佳答案

我对您的帖子给出了另一个答案,现在使用 prepend 而不是 include(仅适用于 ruby​​ 2.x)。第一个是包含在祖先链的顶端,因为第二个在类之后。

让我们看看它在 irb 控制台上是如何工作的:

~/rails/learn/ruby (main) > module A
~/rails/learn/ruby (main) | def cancel!
~/rails/learn/ruby (main) | puts 'cancel from m:A'
~/rails/learn/ruby (main) | super if defined? super
~/rails/learn/ruby (main) | end
~/rails/learn/ruby (main) | end
=> :cancel!
~/rails/learn/ruby (main) > class C
~/rails/learn/ruby (main) | prepend A
~/rails/learn/ruby (main) | def cancel!
~/rails/learn/ruby (main) | puts 'cancel from c:C'
~/rails/learn/ruby (main) | end
~/rails/learn/ruby (main) | end
=> :cancel!
~/rails/learn/ruby (main) > C.ancestors
=> [
[0] #<Class:0x000000035421f0>::A,
[1] #<Class:0x000000035421f0>::C < Object,
[2] Object < BasicObject,
[3] PP::ObjectMixin,
[4] Kernel,
[5] BasicObject
]
~/rails/learn/ruby (main) > C.new.cancel!
cancel from m:A
cancel from c:C
=> nil
~/rails/learn/ruby (main) > class D
~/rails/learn/ruby (main) | include A
~/rails/learn/ruby (main) | def cancel!
~/rails/learn/ruby (main) | puts 'cancel from c:D'
~/rails/learn/ruby (main) | super if defined? super
~/rails/learn/ruby (main) | end
~/rails/learn/ruby (main) | end
=> :cancel!
~/rails/learn/ruby (main) > D.ancestors
=> [
[0] #<Class:0x000000035421f0>::D < Object,
[1] #<Class:0x000000035421f0>::A,
[2] Object < BasicObject,
[3] PP::ObjectMixin,
[4] Kernel,
[5] BasicObject
]
~/rails/learn/ruby (main) > D.new.cancel!
cancel from c:D
cancel from m:A
=> nil

希望对您的问题有所帮助。

关于ruby-on-rails - 检查 mixee 类上是否定义了方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29174034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com