Reloading lib files without a restart server in Rails 3.1

I have some modules inside lib folder in rails ie:

/ Library / MyApp / Library / **

I work on them in development but every time I have to restart the server. I went through a few different questions on SO, but most of them are not for 3.1 rails.

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 general way to do this? Its very time consuming to restart the server every time!

+3


source to share


2 answers


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

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

      

Beware that your module and class names must follow the naming convention in order to work with autoloading. for example, if you have a lib / myapp / cool.rb file, then your constant for class / module declaration in cool.rb should look like this:

Myapp::Cool

      



If you have a lib / myapp / lib / cool.rb file and you want to use Cool as the class / module name instead of Myapp :: Lib :: Cool, your autoload should look like this:

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

      

While you are working in devmode, rails will automatically reload all classes / modules that are in the autoload path and follow naming conventions.

+13


source


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.

+2


source







All Articles