LoginSignup
5
7

More than 5 years have passed since last update.

Railsの名前空間について自分用メモ

Last updated at Posted at 2016-06-11

controllerのネームスペース

resource見る側のcontextを表すようにする感じ。
管理者からしか見ないものを作るなら、adminなどをつける。
apiから見られるものを管理したいからapi
バージョン管理したいapi/v1

modelのネームスペース

controllerにnamespaceがついているからといって、つける必要はない。

#bad
Admin::ArticleController
Admin::Article

#good?
Admin::ArticleController
Article

articleは管理者から見ても、ユーザーからみてもarticle。
名前がどうしても被ってしまう時に、コンテキストとして使う。
group/message
article/message
など。

必要ないネームスペースを付与すると
いろいろなところで記述が冗長になる。
active_recordのリレーションにclass_nameoptionの指定や、
URLヘルパーに配列で、ネームスペースを渡さなければならない等。
生産性を上げるため、出来るだけ避けるべきだと思う。

moduleのネームスペース

共通で利用されるものはconcernsにまとめる。

機能をコンテキストで分けて管理したい場合。
userの管理画面側でしかつかわない機能
user/admin
userの状態に関する機能をまとめたい
user/status
それらをuserでincludeする。

参考

http://qiita.com/srockstyle/items/5b0bf6fe2a78e1aa7363
http://qiita.com/blueplanet/items/522cc8364f6cf189ecad
http://techracho.bpsinc.jp/hachi8833/2014_03_03/15619
http://postd.cc/how-dhh-organizes-his-rails-controllers/

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7