Automatically reload rails module

前端 未结 3 1236
再見小時候
再見小時候 2021-01-20 18:04

I\'m developing a ruby module that I include in my rails app. I want it to be reloaded automatically when it changes. I\'ve done extensive googling, and looked at the variou

相关标签:
3条回答
  • 2021-01-20 18:11

    I spent sometimes to research this issue as well.

    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.

    0 讨论(0)
  • 2021-01-20 18:24

    I found how to do this:

    1. Make sure FooModule is in lib/foo_module.rb.
    2. Use require_dependency to require your external library in lib/foo_module.rb.

    These steps are both required, and no others are required.

    0 讨论(0)
  • 2021-01-20 18:37

    There are two separate problems here.

    The simpler of which is that you are using require, when you want load.

    • require will evaluate the code in a file once, no matter how many times that file/module is required.

    • load will evaluate the code in a file each time that file is loaded.

    require is preferred to load used so that the files are not evaluated multiple times when many files depend on them.

    The short version is that load can be used to reload modules that have already been loaded by require.


    The more complicated problem is automatically reloading a module on change.

    One of the possible duplicates listed in the question links to here. Which suggests prefixing any code that depends on your module with a conditional load of your module if it has changed since loading. You'll need to use a global variable to keep track of when a file was loaded.

    N.B.: this should not be used on a production server, but should be fine on a development server or console.

    0 讨论(0)
提交回复
热议问题