Make sure that attribute_for_inspect respect filter_attributes

Before this change while inspect was respecting that option, attribute_for_inspect
was not.

I also changed inspect to use attribute_for_inspect so we make sure the behavior
is consistent in the two places and simplified the implementation.

Fixes #40725.
This commit is contained in:
Rafael Mendonça França 2020-12-02 23:01:34 +00:00
parent 9f1623bd34
commit d04f74dd72
No known key found for this signature in database
GPG Key ID: FC23B6D0F1EEE948
3 changed files with 21 additions and 16 deletions

View File

@ -285,7 +285,7 @@ module ActiveRecord
attr_name = attr_name.to_s
attr_name = self.class.attribute_aliases[attr_name] || attr_name
value = _read_attribute(attr_name)
format_for_inspect(value)
format_for_inspect(attr_name, value)
end
# Returns +true+ if the specified +attribute+ has been set by the user or by a
@ -407,13 +407,19 @@ module ActiveRecord
end
end
def format_for_inspect(value)
if value.is_a?(String) && value.length > 50
"#{value[0, 50]}...".inspect
elsif value.is_a?(Date) || value.is_a?(Time)
%("#{value.to_s(:inspect)}")
else
def format_for_inspect(name, value)
if value.nil?
value.inspect
else
inspected_value = if value.is_a?(String) && value.length > 50
"#{value[0, 50]}...".inspect
elsif value.is_a?(Date) || value.is_a?(Time)
%("#{value.to_s(:inspect)}")
else
value.inspect
end
inspection_filter.filter_param(name, inspected_value)
end
end

View File

@ -668,14 +668,7 @@ module ActiveRecord
inspection = if defined?(@attributes) && @attributes
self.class.attribute_names.collect do |name|
if _has_attribute?(name)
attr = _read_attribute(name)
value = if attr.nil?
attr.inspect
else
attr = format_for_inspect(attr)
inspection_filter.filter_param(name, attr)
end
"#{name}: #{value}"
"#{name}: #{attribute_for_inspect(name)}"
end
end.compact.join(", ")
else

View File

@ -31,7 +31,13 @@ class FilterAttributesTest < ActiveRecord::TestCase
end
end
test "string filter_attributes perform pertial match" do
test "filter_attributes affects attribute_for_inspect" do
Admin::User.all.each do |user|
assert_equal "[FILTERED]", user.attribute_for_inspect(:name)
end
end
test "string filter_attributes perform partial match" do
ActiveRecord::Base.filter_attributes = ["n"]
Admin::Account.all.each do |account|
assert_includes account.inspect, "name: [FILTERED]"