Skip to content

Commit e3a5456

Browse files
committed
Allow Safeguards to be added and/or overridden outside of core
1 parent f4780bc commit e3a5456

File tree

2 files changed

+209
-133
lines changed

2 files changed

+209
-133
lines changed

lib/database_cleaner/safeguard.rb

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,27 @@ def initialize
2222
end
2323
end
2424

25-
class AllowedUrl
25+
# Base class for core-consumers to implement Safeguards
26+
#
27+
class Base
28+
def run
29+
raise NotImplementedError
30+
end
31+
32+
def self.inherited(subclass)
33+
DatabaseCleaner::Safeguard.registry << subclass
34+
DatabaseCleaner::Safeguard.deprecated_registry.reject! do |const|
35+
subclass.name.split("::").last == const.name.split("::").last
36+
end
37+
end
38+
end
39+
40+
# Just a marker class for Safeguards implemented by core that are kept for backwards compatibility.
41+
# Adapters should implement their own Safeguards using Safeguard::Base.
42+
#
43+
class Deprecated; end
44+
45+
class AllowedUrl < Deprecated
2646
def run
2747
return if skip?
2848
raise Error::UrlNotAllowed if database_url_not_allowed?
@@ -39,8 +59,7 @@ def skip?
3959
end
4060
end
4161

42-
43-
class RemoteDatabaseUrl
62+
class RemoteDatabaseUrl < Deprecated
4463
LOCAL = %w(localhost 127.0.0.1)
4564

4665
def run
@@ -73,7 +92,7 @@ def skip?
7392
end
7493
end
7594

76-
class Production
95+
class Production < Deprecated
7796
KEYS = %w(ENV APP_ENV RACK_ENV RAILS_ENV)
7897

7998
def run
@@ -96,14 +115,30 @@ def skip?
96115
end
97116
end
98117

99-
CHECKS = [
118+
def run
119+
self.class.registry.each { |const| const.new.run }
120+
self.class.deprecated_registry.each { |const| const.new.run }
121+
end
122+
123+
@registry = []
124+
@deprecated_registry = [
100125
RemoteDatabaseUrl,
101126
Production,
102127
AllowedUrl
103128
]
104129

105-
def run
106-
CHECKS.each { |const| const.new.run }
130+
class << self
131+
attr_reader :registry
132+
attr_reader :deprecated_registry
133+
134+
def reset_registry!
135+
@registry = []
136+
@deprecated_registry = [
137+
RemoteDatabaseUrl,
138+
Production,
139+
AllowedUrl
140+
]
141+
end
107142
end
108143
end
109144
end

0 commit comments

Comments
 (0)