So have a rails 5 project and would like to load a directory like this
/app
/services
/user
foo.rb
as the constant ::Services::User::Foo
Does anyone have experience in getting rails autoload paths to load the constants in this manner?
foo.rb
module Services
module User
class Foo
end
end
end
SOLUTION
Add this to your application.rb file
config.autoload_paths << Rails.root.join('app')
See discussions here on autoloading
https://github.com/rails/rails/issues/14382#issuecomment-37763348 https://github.com/trailblazer/trailblazer/issues/89#issuecomment-149367035
Auto loading
You need to define
Services::User::Foo
insideapp/services/services/user/foo.rb
If you don't want this weird subfolder duplication, you could also move
services
toapp/models/services
orlib/services
.You could also leave
foo.rb
inapp/services/user/foo.rb
, but it should defineUser::Foo
.Eager loading
If you don't need any magic with namespaces and class names, it is pretty straightforward :
This will eagerly load any Ruby script inside
app/services
and any subfolder.