简体   繁体   English

在Rails 3.1中重新加载lib文件而不重启dev服务器

[英]Reload lib files without restart dev server in Rails 3.1

I have some modules inside the lib folder in rails ie: 我在rails中的lib文件夹中有一些模块,即:

/lib/myapp/lib/** / LIB / MyApp的/ LIB / **

I am working on them in development, however each time I have to restart server. 我正在开发它们,但每次我必须重新启动服务器。 I have been through a number of different questions on SO but most of them are for not for rails 3.1 我在SO上遇到了很多不同的问题,但大多数问题都不适用于rails 3.1

I currently have an initializer that does this; 我目前有一个初始化器,可以做到这一点;

if Rails.env == "development"
  lib_reloader = ActiveSupport::FileUpdateChecker.new(Dir["lib/**/*"], true) do
    Rails.application.reload_routes! # or do something better here
  end

  ActionDispatch::Callbacks.to_prepare do
    lib_reloader.execute_if_updated
  end
end

if Rails.env == "development"
  lib_reloader = ActiveSupport::FileUpdateChecker.new(Dir["lib/myapp/lib/*"], true) do
    Rails.application.reload_routes! # or do something better here
  end

  ActionDispatch::Callbacks.to_prepare do
    lib_reloader.execute_if_updated
  end
end

Is there a generic way to do this? 有没有通用的方法来做到这一点? Its very time consuming having to restart the server every single time! 每次都要重启服务器非常耗时!

Get rid of the initializer and in your application.rb file put following line: 摆脱初始化程序并在你的application.rb文件中放入以下行:

config.autoload_paths += Dir["#{config.root}/lib/**/"]

One thing to watch out is that your module and class names should follow the naming convention for autoreload to work. 需要注意的一点是,您的模块和类名应遵循自动重载的命名约定。 for example if you have file lib/myapp/cool.rb, then your constant for class/module declaration in cool.rb should look like this: 例如,如果你有文件lib / myapp / cool.rb,那么cool.rb中类/模块声明的常量应如下所示:

Myapp::Cool

If you have file lib/myapp/lib/cool.rb and you want it to use Cool as class/module name instead of Myapp::Lib::Cool then your autoload should look like this: 如果您有文件lib / myapp / lib / cool.rb并且您希望它使用Cool作为类/模块名称而不是Myapp :: Lib :: Cool,那么您的自动加载应该如下所示:

config.autoload_paths += Dir["#{config.root}/lib/myapp/lib/**/"]

As long as you are running in devmode, rails will automatically reload all classes/modules that are in autoload path and follow naming conventions. 只要您在devmode中运行,rails就会自动重新加载自动加载路径中的所有类/模块并遵循命名约定。

Add to application_controller.rb or your base controller: 添加到application_controller.rb或您的基本控制器:

  before_filter :dev_reload if Rails.env.eql? 'development'

  def dev_reload
    # add lib files here
    ["rest_client.rb"].each do |lib_file|
      ActiveSupport::Dependencies.load_file lib_file
    end
  end

Worked for me. 为我工作。

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

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