如何在每个请求中重新加载/lib目录中的文件?

3
Rails会在每个请求中加载控制器、帮助程序和模型。
我的控制器有一堆包含共享操作的模块。
每次更改模块时,我都需要重新启动Rails才能使操作的更改生效。
你有什么想法可以告诉Rails也重新加载这些模块吗?
更新:
我的目录结构如下:
app/ controllers/ app1/ users_controller.rb app2/ users_controller.rb lib/ templates/ controllers/ users_controller_template.rb
App1 :: UsersController和App2 :: UsersController都像这样加载UsersControllerTeplate:
# app/controllers/app1/users_controller.rb
class App1::UsersController < App1::ApplicationController
  require "templates/controllers/users_controller_template"
  include Templates::Controllers::UsersControllerTemplate
end

# templates/controllers/users_controller_template.rb
module Templates::Controllers::UsersControllerTemplate

  def self.included(base)
    base.class_eval do
      # some class macros called here
    end
  end
  
  # actions defined here
  def index
  end

end

在 application.rb 中,我已经添加了:

config.autoload_paths += %W{ #{config.root}/lib/templates/ }

但是我仍然需要重新加载服务器才能看到在users_controller_template.rb中所做的更改。有任何想法吗?

我认为Shotgun是解决方案:https://github.com/rtomayko/shotgun - Evgeny Shadchnev
2个回答

3
你可以将它们添加到你的应用程序.rb文件中的autoload_paths,它们将随着模型和控制器自动重新加载。
config.autoload_paths << "#{config.root}/lib"

2
我已经添加了:config.autoload_paths += %W( #{config.root}/lib/templates/controllers )我的控制器从 /lib/templates/controllers 中加载模块这似乎仍然没有在每个请求上重新加载?- 有什么想法吗? - bodacious
1
这可能与您的类/模块定义有关。对于Rails自动加载文件,文件结构必须匹配模块/类嵌套。例如,lib/templates/controllers/my_class.rb应该定义为Templates::Controllers::MyClass。此外,我认为您不需要显式添加嵌套路径以使自动加载正常工作。 - Pan Thomakos
我的原始帖子不起作用吗?它应该可以 - Rails 在查找autoload路径时是递归的。 我建议完全删除config.autoload_paths +=%W {#{config.root}/lib/templates /}行。此外,您无需在控制器中要求文件,因为它是autoload_paths的一部分。您应该完全删除require行。 - Pan Thomakos
我已经删除了“require”- 仍然重新加载- 谢谢!但是它没有自动加载模块- 即使只有“#{config.root}/lib”在我的autoload_paths中。 - bodacious
我目前无法重现你的错误。除此之外,我会确保 lib 不在你的 autoload_once_paths 中,但是你的代码似乎是正确的。我建议你尝试创建一个新的 Rails 应用程序,并将嵌套的 lib 目录添加到你的 autoload_paths 中以验证其是否有效。 - Pan Thomakos

2
config/application.rb中:
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

这将重新加载lib文件夹中的任何Ruby文件,以及lib子目录中的任何Ruby文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接