在rails应用程序目录中将文件夹加载为模块常量的方法 [英] Way to load folder as module constant in rails app directory

查看:44
本文介绍了在rails应用程序目录中将文件夹加载为模块常量的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以有一个 rails 5 项目,想加载这样的目录

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

/app
  /services
    /user
      foo.rb

作为常量::Services::User::Foo

as the constant ::Services::User::Foo

有没有人有让 Rails 自动加载路径以这种方式加载常量的经验?

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

解决方案

将此添加到您的 application.rb 文件

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-37763348https://github.com/trailblazer/trailblazer/issues/89#issuecomment-149367035

推荐答案

自动加载

你需要在app/services/services/user/foo.rb

如果你不想要这个奇怪的子文件夹重复,你也可以将 services 移动到 app/models/serviceslib/services.

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

你也可以将 foo.rb 留在 app/services/user/foo.rb 中,但它应该定义 User::Foo.

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

如果您不需要任何关于命名空间和类名的魔法,那就很简单了:

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}

这将立即加载 app/services 和任何子文件夹中的任何 Ruby 脚本.

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

这篇关于在rails应用程序目录中将文件夹加载为模块常量的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆