gpt4 book ai didi

ruby-on-rails - 如何正确覆盖模块混入的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 16:06:18 25 4
gpt4 key购买 nike

我正在使用 Ruby 1.9.2 和 Ruby on Rails 3.2.2。我有以下情况:

class MyClass < ActiveRecord::Base
include MyModule1
include MyModule2
include ...

# Note: This method statement should override the method mixedin by MyModule1.
def my_method(*args)
# ...
end
end

module MyModule1
def my_method(*args)
raise "NotImplementedError - The :my_method is not implemented yet"
end
end

# /app/views/layouts/application.html.erb
if @my_class.my_method
All right!
end

当我启动 Web 应用程序浏览页面时,我收到错误 “NotImplementedError - The :my_method is not implemented yet”,即使我覆盖了 my_method MyClass 包括 MyModule(如您在上面的代码中所读)。它发生是因为它加载了类之前的 View 吗?或者是什么?我应该如何处理这种情况才能使 MyClass 正确覆盖 my_method

最佳答案

一定有比您在此处显示的更多的内容,因为您在此处显示的代码肯定不会调用 #my_method来自 MyModule1 .非常仔细地检查 def my_methodMyClass没有拼错,它实际上出现在 class MyClass 中 block ,而不是在嵌套内 class << self block 或类似的东西。

如果没有显示任何内容,请转到代码中出现异常的地方,并添加几个调试打印语句:

<% p @my_class.class %>
<% p @my_class.class.ancestors %>

查看控制台中打印的内容。

关于ruby-on-rails - 如何正确覆盖模块混入的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100874/

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