Skip to content

Commit 7fe794c

Browse files
authored
Merge pull request rails#50053 from Shopify/deprecator-source-templates
ActiveSupport::Deprecation handle blaming generated code
2 parents 5b45a58 + c2be3ea commit 7fe794c

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

activesupport/lib/active_support/deprecation/reporting.rb

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,17 @@ def extract_callstack(callstack)
142142
return _extract_callstack(callstack) if callstack.first.is_a? String
143143

144144
offending_line = callstack.find { |frame|
145-
frame.absolute_path && !ignored_callstack(frame.absolute_path)
145+
# Code generated with `eval` doesn't have an `absolute_path`, e.g. templates.
146+
path = frame.absolute_path || frame.path
147+
path && !ignored_callstack?(path)
146148
} || callstack.first
147149

148150
[offending_line.path, offending_line.lineno, offending_line.label]
149151
end
150152

151153
def _extract_callstack(callstack)
152154
warn "Please pass `caller_locations` to the deprecation API" if $VERBOSE
153-
offending_line = callstack.find { |line| !ignored_callstack(line) } || callstack.first
155+
offending_line = callstack.find { |line| !ignored_callstack?(line) } || callstack.first
154156

155157
if offending_line
156158
if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/)
@@ -162,9 +164,10 @@ def _extract_callstack(callstack)
162164
end
163165

164166
RAILS_GEM_ROOT = File.expand_path("../../../..", __dir__) + "/"
167+
LIB_DIR = RbConfig::CONFIG["libdir"]
165168

166-
def ignored_callstack(path)
167-
path.start_with?(RAILS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG["rubylibdir"])
169+
def ignored_callstack?(path)
170+
path.start_with?(RAILS_GEM_ROOT, LIB_DIR)
168171
end
169172
end
170173
end

activesupport/test/deprecation_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -951,6 +951,18 @@ def method
951951
assert_equal __LINE__ - 2, @callstack.first.lineno
952952
end
953953

954+
class_eval(<<~RUBY, "/path/to/template.html.erb", 1)
955+
def generated_method_that_call_deprecation(deprecator)
956+
deprecator.warn("Here", caller_locations(0, 10))
957+
end
958+
RUBY
959+
960+
test "warn deprecation can blame code generated with eval" do
961+
@deprecator.behavior = ->(message, *) { @message = message }
962+
generated_method_that_call_deprecation(@deprecator)
963+
assert_equal "DEPRECATION WARNING: Here (called from generated_method_that_call_deprecation at /path/to/template.html.erb:2)", @message
964+
end
965+
954966
private
955967
def method_that_emits_deprecation(deprecator)
956968
deprecator.warn

0 commit comments

Comments
 (0)