开发者

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. 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!


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. 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.


They are identical, second is just syntax sugar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜