Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload lib files without restart dev server in Rails 3.1

I have some modules inside the lib folder in rails i.e.:

/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

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!

like image 880
Charlie Davies Avatar asked Dec 05 '22 17:12

Charlie Davies


2 Answers

Get rid of the initializer and in your application.rb file put following line:

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:

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:

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.

like image 193
Iuri G. Avatar answered Dec 23 '22 05:12

Iuri G.


Add to application_controller.rb or your base controller:

  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.

like image 39
Haris Krajina Avatar answered Dec 23 '22 04:12

Haris Krajina