Rails模块与模型类名称冲突

时间:2019-04-16 15:28:09

标签: ruby-on-rails ruby

在我们的Rails应用中,我们有一些模型,例如:

module ProductName
  class StoreBuild
  end
end

然后我们有一些工作人员,例如:

module ProductName
  module StoreBuild
    class StoreBuildWorker
    end
  end
end

然后我们将这些工人称为:

ProductName::StoreBuild::StoreBuildWorker.perform_async(@store_build.id)

但是有时我们会遇到错误:

TypeError:
  StoreBuild is not a module

当我们从最后一行检查StoreBuild时,它认为是模型类而不是我们正在引用的worker模块会导致错误...

如何停止与类名冲突的模块?

令人讨厌的是,Rails不在顶级文件夹中使用名称空间,因此这意味着要使用相同名称空间的模型和工作程序会发生冲突,因为它们本身没有任何名称空间。

3 个答案:

答案 0 :(得分:3)

我的猜测是,因为它们都在同一个命名空间中,所以您不能给它们起相同的名字。尝试将模块名称从StoreBuild更改为其他名称。它应该可以解决您的问题。会为此共享更多文档。

答案 1 :(得分:3)

由于Rails的自动加载层次结构,此操作失败。仔细检查Autoloading and Reloading Constants,以了解其工作原理。

Rails看到ProductName::StoreBuild,然后将其引用作为类而不是模块进行缓存。当您有了ProductName::StoreBuild::StoreBuildWorker时,它会说“嗯,现在是一个模块”,然后吓坏了。

轶事:您的应用可能井井有条。

答案 2 :(得分:0)

The error message is telling you that there is a conflict since you are redefining ProductName::StoreBuild as a module where you have previously defined the same thing as a class.

If you don't want to rename anything, you can nest modules within a class if it makes sense in the namespacing of your app.

So if you have a class:

module ProductName
  class StoreBuild
  end
end

You can embed another class underneath it like so:

module ProductName
  class StoreBuild
    class StoreBuildWorker
    end
  end
end
相关问题