Skip to content

Commit b5a758d

Browse files
jhawthornbyroot
andauthored
Avoid checking defined?(@html_safe) (rails#45620)
We should not need to check defined? here because we are only interested in whether @html_safe is truthy or falsy. We can use an aliased attr_reader to make this even faster by skipping both method dispatch. Co-authored-by: Jean Boussier <[email protected]>
1 parent 06e9fbd commit b5a758d

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

activesupport/lib/active_support/core_ext/string/output_safety.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,9 +261,9 @@ def %(args)
261261
self.class.new(super(escaped_args))
262262
end
263263

264-
def html_safe?
265-
defined?(@html_safe) && @html_safe
266-
end
264+
attr_reader :html_safe
265+
alias_method :html_safe?, :html_safe
266+
remove_method :html_safe
267267

268268
def to_s
269269
self

activesupport/test/safe_buffer_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,13 @@ def test_titleize
171171
assert_not_predicate @buffer.dup, :html_safe?
172172
end
173173

174+
test "Can call html_safe on a safe buffer" do
175+
@buffer = "hello".html_safe
176+
extra_safe = @buffer.html_safe
177+
assert_equal "hello", extra_safe
178+
assert_predicate extra_safe, :html_safe?
179+
end
180+
174181
test "Should return safe buffer when added with another safe buffer" do
175182
clean = "<script>".html_safe
176183
result_buffer = @buffer + clean

0 commit comments

Comments
 (0)