How can I automatically reload the gem code for each request in development mode in Rails?

I am developing a Rails application where most of the non-application specific code was written inside various gems, including some Rails engines and some third-party stones, for which I am improving or fixing bugs.

gem 'mygem', path: File.expath_path('../../mygem', __FILE__) 

Since most of the code in these gems is indeed part of the application, it still changes frequently. I would like to be able to use the Rails function, where the code is reloaded for each request during development (i.e. when config.cache_classes is false), but by default this only runs in the normal application structure.

How to configure Rails to reload gem code for each request, as with application code?

+2
source share
1 answer

I found through the trial version and the error that several steps are required using ActiveSupport .

  • Add ActiveSupport as a dependency in .gemspec files

     spec.add_dependency 'activesupport' 
  • Enable ActiveSupport :: Dependencies in the top-level module of your gem (this was the most elusive requirement)

     require 'bundler'; Bundler.setup require 'active_support/dependencies' module MyGem unloadable include ActiveSupport::Dependencies end require 'my_gem/version.rb' # etc... 
  • Customize your gem to use autoload. You either manually use ruby autoload declarations to map characters to file names, or use a folder-structure-in-module hierarchy in Rails-style rules (see ActiveSupport #constantize )

  • In each module and class of your gem, add unloadable .

     module MyModule unloadable end 
  • In each file, which depends on the module or class of the gem, including in the gem itself, declare them at the top of each file using require_dependency . See the path of the pearl as necessary to properly resolve the path.

     require_dependency "#{Gem.loaded_specs['my_gem'].full_gem_path}/lib/my_gem/myclass" 

If you get exceptions after modifying the file and submitting a request, make sure you don't miss the dependency.

For some interesting details, see this full Rails (and ruby) autoload post.

+3
source

Source: https://habr.com/ru/post/885559/


All Articles