在 Ruby on Rails 中定义命名空间模型的正确方法
只是想知道在 Rails 中定义命名空间模型的正确方法是什么。我看到它有两种定义。在大多数库中,它们似乎都是这样定义的
module Fruit
class Banana < ActiveRecord::Base
...
end
end
,而 Rails 生成器似乎更喜欢这样。
class Fruit::Banana < ActiveRecord::Base
...
end
它们显然都可以工作,但有什么区别呢?哪个是首选?谢谢!
Just wondering what is the proper way to define a namespaced model in Rails. I've seen it defined in two ways. In most libraries they seem to be defined as such
module Fruit
class Banana < ActiveRecord::Base
...
end
end
whereas the Rails generator seems to prefer this
class Fruit::Banana < ActiveRecord::Base
...
end
They both obviously work but what is the difference? Which is preferred? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们并不相同,更详细的方式将实际定义模块,而更简短的方式将期望它已经被定义。
这将抛出一个
NameError
。但是,如果您这样做,则不会引发错误。
They are not identical, the more verbose way will actually define the module, whereas the shorter way will expect it to be defined already.
That will throw a
NameError
. However if you doit will not throw an error.
它们是相同的,但“更长”的版本允许您向模块添加其他内容。 我更喜欢这样,因为我经常以这种方式将多个小东西打包到一个模块中。
They're the same, but the "longer" version lets you add other stuff to the module. I prefer that since I'll often package multiple small things into a module that way.
它们是相同的,其次只是语法糖。
They are identical, second is just syntax sugar.