Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 - Namespacing models

I am using namespacing in my Rails 5 app to try to keep resources organised.

I've been generating resources using the command line by adding the namespace folder to the generate command.

This makes a folder in the models folder for the main folder which the namespaced files are saved in.

I've since been reading posts from others that suggest namespacing models is not a good idea.

An example of what I currently have is:

class Stance::Assessment < ApplicationRecord

It seems to work alright so far.

What is the problem with namespacing models?

If it is a problem, does that mean I can't organise my models into folder groups, or does it mean that the model class doesnt need to be named wiht the "Stance::"?

like image 518
Mel Avatar asked Nov 08 '16 02:11

Mel


1 Answers

There is a certain cost of complexity involved with "namespacing" your models. Ruby does not actually have true namespaces. Rather it has has modules which provide encapsulation.

Rails and ActiveRecord was designed around placing your application code in the Main object (the global object). While this might seem like a bad practice it is very simple and works well with the convention over configuration approach. It also allows a much simpler autoloading scheme and avoids the need to nest every single file in an additional folder.

Namespacing does have great organizational merits though and lets you avoid collisions. But there are a few minor aches in the backside:

  • table prefixes, having the generated table names like my_app_projects_tasks is really inconvenient when you need to write a custom join.
  • You need to override ActiveModel::Naming so that it does not look for paths like my_app_projects_tasks_path when using the polymorphic route helpers.
  • You need to explicitly set the class_name option when creating associations or override how ActiveRecord resolves constant names.
like image 197
max Avatar answered Nov 13 '22 11:11

max