简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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