Namespacing models in a Rails application
I had a discussion recently with a friend of mine who is also a RoR developer. We argued about how Rails models should be managed. Personally I like to leave in the default namespace only the root models (eg User, Article, Bill etc.), and the dependent models go to a module (eg User::Profile, User::Activity) with the name of the root model they are associated with.
On the other hand, I've seen many projects which had like 100 models in the default namespace called like user_profile, user_activity and so on. Judging by Java (Spring) development, java community tends to organize class in packages and have them grouped logically, which I find very appealing.
So the question is: are there any drawback in grouping models in modules (except the extra :class_name in relation definition) and are there any specific reasons why people usually don't do it?
Although namespacing has its advantages, it does require adding exceptions throughout your models. Foo::Bar presumes a table name of bars
and likewise bar_id
for associations, whereas you might prefer foo_bars
and foo_bar_id
to be used instead.
If you really feel strongly about this, you might want to see if there's an add-on that fixes this for you, or implement your own extension that does.
The only case when I've used namespaces is for add-ons that are to be used in third party applications where I don't want to claim root-level model names as that would be annoying. The extra effort in this case is worth-while.
If you're bothered by seeing 100+ model files without any grouping, you'll probably be equally annoyed by seeing 100+ tables with no grouping, and that's generally something you can't fix.
Controllers lend themselves to grouping quite naturally, but models aren't as easily accommodated, at least not with stock ActiveRecord.
链接地址: http://www.djcxy.com/p/58554.html上一篇: MonoTouch中使用Monodevelop中的环境变量
下一篇: 命名空间模型在Rails应用程序中