balanv
balanv

Reputation: 10898

Organizing models/controllers and classes in rails in subfolders

I am working in a Rails project in which i have used the below names for model/controller and class files

/app/models/friends/friend.rb
/app/controllers/friends/friends_controller.rb
/lib/classes/friends/friend.rb

I tried to add all the models, controllers and class files in autoload path in application.rb. But i am facing issues since the class names are same.

How should i handle this? and organize files in such a way that files are organized with name spaces.

Thanks, Balan

Upvotes: 0

Views: 642

Answers (2)

CuriousMind
CuriousMind

Reputation: 34175

A much better approach would be to use Rails Engines & divide your app in isolated modules.

rails plugin new friends --full --mountable --dummy-path spec/dummy

the above command will generate a full mountable engine with isolated namespace, meaning that all the controllers and models from this engine will be isolated within the namespace of the engine. For instance, the Post model later will be called Friends::Post, and not simply Post. to mount this app inside your main rails app, you need do two things:

Add entry to Gemfile

gem 'friends', path: "/path/to/friends/engine"

And then add route to config/routes.rb

mount Friends::Engine, at: "/friends"

For more information on this approch, checkout:

Upvotes: 1

TM.
TM.

Reputation: 3741

The class names are same but path's are different, and you don't need to add classes to autoload except /lib/classes/friends/friend.rb

Did you tried the following way:

# app/models/friends/friend.rb
class Friends::Friends
  #...
end
# Friends::Friends.new

# app/controllers/friends/friends_controller.rb
class Friends::FriendsController < ApplicationController
  #...
end

# lib/classes/friends/friend.rb
module Classes
  module Friends
    class Friends
      #...
    end
  end
end
# Classes::Friends::Friends.new

To add lib files to autoload add following to your applicaion.rb

config.autoload_paths += %W(#{config.root}/lib)

Upvotes: 0

Related Questions