Way to load folder as module constant in rails app

2020-07-06 06:22发布

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

1条回答
Fickle 薄情
2楼-- · 2020-07-06 07:05

Auto loading

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

If you don't want this weird subfolder duplication, you could also move services to app/models/services or lib/services.

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

Eager loading

If you don't need any magic with namespaces and class names, it is pretty straightforward :

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

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

查看更多
登录 后发表回答