Can Rails console reload modules under lib?

Ruby on-RailsConsole

Ruby on-Rails Problem Overview


I have a module in my Rails project under lib. I run 'rails c' and do some experimenting in the console. I make a change to the module under lib, type 'reload!' from the console and it doesn't reload the file. I have to quit the console and restart, which is real pain.

Is there a better way to reload that file?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try this:

load "#{Rails.root}/lib/yourfile.rb"

Solution 2 - Ruby on-Rails

In case anyone interested, here's my findings on how to auto-reload require files in Rails without restarting server.

The solution is now available as a Ruby gem require_reloader.

Solution 3 - Ruby on-Rails

this is the monkeypatch that could help you, paste this in rails console (or you could put this code in a monkeypatch file - although I don't recommend monkeypatching Object with an utility method):

class Object
  def self.reload_myself!
    method = (self.instance_methods(false) + self.methods(false)).select{|method| method.to_s[0] =~ /[A-Za-z]/}.last
    if method
      if self.instance_methods(false).index method
        method = self.instance_method(method)
      elsif
        method =  self.method(method)
      end

      if (method.source_location)
        source_location = method.source_location[0]
        puts "reloading: #{source_location}"
        load "#{source_location}"
      else
        puts "could not reload #{self.name}"
      end
    end
  end
end

and you can call

reload_myself!

on any object to reload its source code.

Solution 4 - Ruby on-Rails

Add the following to config/initializers/reload.rb

class Object
  def reload_lib!
    Dir["#{Rails.root}/lib/**/*.rb"].map { |f| [f, load(f) ] } #.all? { |a| a[1] } 
    # uncomment above if you don't want to see all the reloaded files
  end
end

You can now reload all the files in lib by typing reload_lib! in the console

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChip CastleView Question on Stackoverflow
Solution 1 - Ruby on-RailsNullRefView Answer on Stackoverflow
Solution 2 - Ruby on-RailsHuiming TeoView Answer on Stackoverflow
Solution 3 - Ruby on-RailsWouter VegterView Answer on Stackoverflow
Solution 4 - Ruby on-RailsAbdoView Answer on Stackoverflow