bgr11n
bgr11n

Reputation: 169

Proper rails model namespacing

Recently I've started a new rails project just for fun and decided to use namespacing in models. And I have some difficulties.

For example, I have model Party:

# app/models/party.rb

class Party < ActiveRecord::Base
end

And each party will have Chat:

# app/models/party/chat.rb

module Party
  class Chat < ActiveRecord::Base
  end
end

The question is when I call Party how Rails will figure out if I call module Party or class Party?

Upvotes: 2

Views: 550

Answers (1)

Jonathan Allard
Jonathan Allard

Reputation: 19249

Indeed, if you do that, Ruby will complain because Party can't be a module and a class at the same time. So at least, Party would need to remain a class.

Now as the "Rails way" is concerned, we don't usually subclass our associations (ie. your Chat will probably belong_to a Party), we just put all our models in the root namespace (unless one has a good reason to). So you'd have Party at app/models/party.rb and Chat at app/models/chat.rb.

I'm guessing one would make a namespaced subclass Party::Chat only if there's a different ::Chat already present, and even that could lead to trouble with Ruby's constant lookup which is sometimes counter-intuitive.

Upvotes: 4

Related Questions