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 "        WARNING: good_migrations is unable to ensure that your migrations are\n          not inadvertently loading application code, because your application\n          uses the zeitwerk autoloader (`config.autoloader = :zeitwerk`), but\n          is using a version prior to zeitwerk 2.5.0, which adds an on_load\n          hook that good_migrations can latch onto.\n\n        Solution: Ensure that zeitwerk isn't pinned below 2.5.0 in your\n          Gemfile and try running `bundle update zeitwerk`.\n\n      UNSUPPORTED\n    end\n  else\n    @disabled = false\n    ActiveSupport::Dependencies.class_eval do\n      extend Module.new {\n        def load_file(path, const_paths = loadable_constants_for_path(path))\n          GoodMigrations::PatchesAutoloader.instance.prevent_autoload_if_necessary!(path)\n          super\n        end\n      }\n    end\n  end\nend\n".strip_heredoc

#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