The way to load a folder as a module constant in the rails application directory

So I have a rails 5 project and would like to download a directory like this

/app /services /user foo.rb 

as a constant :: Services :: User :: Foo

Does anyone have any experience in getting auto-loading paths for rails to load constants this way?


foo.rb

 module Services module User class Foo end end end 

DECISION

Add this to your application.rb file

config.autoload_paths << Rails.root.join('app')

See discussions here on startup

https://github.com/rails/rails/issues/14382#issuecomment-37763348 https://github.com/trailblazer/trailblazer/issues/89#issuecomment-149367035

+5
source share
1 answer

Auto Download

You need to define Services::User::Foo inside app/services/services/user/foo.rb

If you do not need this strange copy of a subfolder, you can also move services to app/models/services or lib/services .

You can also leave foo.rb in app/services/user/foo.rb , but it should define User::Foo .

Unwanted loading

If you don't need magic with class names and names, it's pretty simple:

 Dir[Rails.root.join('app/services/**/*.rb')].each{|rb| require rb} 

This will load any Ruby script inside app/services and any subfolder.

+4
source

Source: https://habr.com/ru/post/1260671/


All Articles