Class: GoodMigrations::PatchesAutoloader

Inherits:
Object
  • Object
show all
Defined in:
lib/good_migrations/patches_autoloader.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePatchesAutoloader

Returns a new instance of PatchesAutoloader.



7
8
9
10
11
12
# File 'lib/good_migrations/patches_autoloader.rb', line 7

def initialize
  @permits_autoload = PermitsAutoload.new
  @raises_load_error = RaisesLoadError.new

  @disabled = false
end

Class Method Details

.instanceObject



3
4
5
# File 'lib/good_migrations/patches_autoloader.rb', line 3

def self.instance
  @instance ||= new
end

Instance Method Details

#patch!Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/good_migrations/patches_autoloader.rb', line 20

def patch!
  if Rails.singleton_class.method_defined?(:autoloaders) &&
      Rails.autoloaders.zeitwerk_enabled?
    if Rails.autoloaders.main.respond_to?(:on_load) &&
        Rails.autoloaders.main.method(:on_load).arity <= 0
      @disabled = false
      Rails.autoloaders.each do |loader|
        loader.on_load do |_, _, path|
          GoodMigrations::PatchesAutoloader.instance.prevent_autoload_if_necessary!(path)
        end
      end
    else
      warn <<-UNSUPPORTED.strip_heredoc
        WARNING: good_migrations is unable to ensure that your migrations are
          not inadvertently loading application code, because your application
          uses the zeitwerk autoloader (`config.autoloader = :zeitwerk`), but
          is using a version prior to zeitwerk 2.5.0, which adds an on_load
          hook that good_migrations can latch onto.

        Solution: Ensure that zeitwerk isn't pinned below 2.5.0 in your
          Gemfile and try running `bundle update zeitwerk`.

      UNSUPPORTED
    end
  else
    @disabled = false
    ActiveSupport::Dependencies.class_eval do
      extend Module.new {
        def load_file(path, const_paths = loadable_constants_for_path(path))
          GoodMigrations::PatchesAutoloader.instance.prevent_autoload_if_necessary!(path)
          super
        end
      }
    end
  end
end

#prevent_autoload_if_necessary!(path) ⇒ Object



14
15
16
17
18
# File 'lib/good_migrations/patches_autoloader.rb', line 14

def prevent_autoload_if_necessary!(path)
  return if @disabled || @permits_autoload.permit?(path)

  @raises_load_error.raise!(path)
end

#unpatch!Object



57
58
59
# File 'lib/good_migrations/patches_autoloader.rb', line 57

def unpatch!
  @disabled = true
end