简体   繁体   English

在Ruby on Rails中定义命名空间模型的正确方法

[英]Proper way to define a namespaced model in Ruby on Rails

Just wondering what is the proper way to define a namespaced model in Rails. 只是想知道在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 而Rails生成器似乎更喜欢这个

class Fruit::Banana < ActiveRecord::Base
  ...
end

They both obviously work but what is the difference? 它们显然都可以工作,但是有什么区别呢? Which is preferred? 哪个是首选? Thanks! 谢谢!

They are not identical, the more verbose way will actually define the module, whereas the shorter way will expect it to be defined already. 它们并不完全相同,实际上,使用更冗长的方法定义模块,而使用较短的方法将期望已定义模块。

class Fruit::Banana; end

That will throw a NameError . 那会抛出一个NameError However if you do 但是如果你这样做

module Fruit; end
class Fruit::Banana; end

it 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. 更喜欢这样做,因为我经常将多个小东西打包到一个模块中。

它们是相同的,第二只是语法糖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM