Rails 项目中同名的模块和类 [英] module and class with the same name in Rails project
问题描述
今天早些时候我在跑步时遇到了这个问题
sidekiq
我收到以下错误:
<块引用>I, [2015-09-04T12:43:33.723243 #15197] INFO -- : Celluloid 0.17.1.2 在 BACKPORTED 模式下运行.[ http://git.io/vJf3J ]报告不是类/home/andreydeineko/employees/app/models/report.rb:1:in `'
但是 Report
是 AR 类/模型,没有任何拼写错误.
发生错误的原因是,项目中存在先前定义的名为Report
的模块.
为什么会出现这个类和模块名相同的问题?
是否有任何 Ruby/Rails 约定不将类和模块命名为同名?
您不能对 Class
和 Module
重复使用相同的名称.在内部,在 Ruby 中模块被表示为类结构,因此它们共享相同的对象空间.
此外,当您定义模块/类时,您可以将名称作为常量访问.
班级报告定义 foop报告"结尾结尾报告=>报告定义?报告=>不变"
其实你也可以写
Report = Class.new 做定义 foop报告"结尾结尾报告 = Report.new报告.foo
长话短说,如果将Report
定义为Class
,则不能创建同名的Module
.
Earlier today I had this problem, when I was running
sidekiq
I was getting the following error:
I, [2015-09-04T12:43:33.723243 #15197] INFO -- : Celluloid 0.17.1.2 is running in BACKPORTED mode. [ http://git.io/vJf3J ] Report is not a class /home/andreydeineko/employees/app/models/report.rb:1:in `<top (required)>'
but Report
was AR class/model without any typos.
It occurred the error was due to the fact, that in the project there was previously defined module called Report
.
Why is this problem with same class and module name occurred?
Is there any Ruby/Rails convention to not name the class and module with same name?
You cannot reuse the same name for a Class
and a Module
. Internally, in Ruby modules are represented as class structures therefore they share the same object space.
Moreover, when you define a Module/Class, you can access the name as a constant.
class Report
def foo
p "report"
end
end
Report
=> Report
defined? Report
=> "constant"
in fact, you can also write
Report = Class.new do
def foo
p "report"
end
end
report = Report.new
report.foo
Long story short, if you define Report
as Class
, you cannot create a Module
with the same name.
这篇关于Rails 项目中同名的模块和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!