简体   繁体   English

如何在Rails4引擎中添加autoload_path?

[英]How can I add autoload_paths in my Rails4 Engine?

Usually I add the following in config/application.rb to add autload_paths: 通常我在config / application.rb中添加以下内容来添加autload_paths:

config.autoload_paths += Dir[Rails.root.join('app', 'poros', '{**}')]

How can I achieve the same in an engine? 如何在引擎中实现相同的目标? It seems to work when I just use the same code in application.rb in the host app, however I think it's ugly that the code is not in the engine and needs to be added to the host app to make things work. 它似乎在我在主机应用程序中的application.rb中使用相同的代码时工作,但是我认为代码不在引擎中并且需要添加到主机应用程序以使事情有效是很难看的。

The only solution I found to add the load path through the engine is by adding this to lib/engine/engine.rb: 我发现通过引擎添加加载路径的唯一解决方案是将其添加到lib / engine / engine.rb:

config.to_prepare do
  Dir.glob(Rails.root + "../../app/poros/**/*.rb").each do |c|
    require_dependency(c)
  end
end

However there seems to be something fundamentally wrong with this as this leads to problems when I'm doing console reloads (eg it tells me that constants are already defined or that concerns can't execute the include block twice) 然而,这似乎有一些根本性的错误,因为这会在我进行控制台重新加载时导致问题(例如,它告诉我已经定义了常量或者关注点无法执行包含块两次)

What is the right way to do this in the engine itself? 在引擎本身中执行此操作的正确方法是什么? (can't believe this is so hard/uncommon, I have really googled a lot but I can't find a solution) (不敢相信这是如此艰难/不常见,我真的google了很多,但我找不到解决方案)

According to the Rails::Engine documentation , you can add autoload paths in your Railtie like this: 根据Rails :: Engine文档 ,您可以在Railtie中添加自动加载路径,如下所示:

class MyEngine < Rails::Engine
  # Add a load path for this specific Engine
  config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)

  initializer "my_engine.add_middleware" do |app|
    app.middleware.use MyEngine::Middleware
  end
end

If poros is a subdirectory of app, you do not need add it again. 如果poros是app的子目录,则无需再次添加。

All subdirectories of app in the application and engines present at boot time. 应用程序和引擎中应用程序的所有子目录都在启动时出现。 For example, app/controllers. 例如,app / controllers。 They do not need to be the default ones, any custom directories like app/workers belong automatically to autoload_paths. 它们不需要是默认目录,任何自定义目录(如app / workers)都会自动归属于autoload_paths。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM