From 786a0cdadb2d9c70f30124b27981401745cc1c8e Mon Sep 17 00:00:00 2001 From: Alexander Momchilov Date: Mon, 18 Dec 2023 12:45:57 -0500 Subject: [PATCH 1/2] Tidy `OpenStruct#inspect` implementation --- lib/ostruct.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/ostruct.rb b/lib/ostruct.rb index fa882b7..82c89df 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -387,18 +387,18 @@ def delete_field(name, &block) # def inspect ids = (Thread.current[InspectKey] ||= []) - if ids.include?(object_id) - detail = ' ...' + + detail = if ids.include?(object_id) + ' ...' else ids << object_id begin - detail = @table.map do |key, value| - " #{key}=#{value.inspect}" - end.join(',') + @table.map { |k, v| " #{k}=#{v.inspect}" }.join(',') ensure ids.pop end end + ['#<', self.class!, detail, '>'].join end alias :to_s :inspect From 6becba87e5325313f6a35cb15014d00caa937299 Mon Sep 17 00:00:00 2001 From: Alexander Momchilov Date: Mon, 18 Dec 2023 12:48:43 -0500 Subject: [PATCH 2/2] Remove `object_id` use in `OpenStruct#inspect` --- lib/ostruct.rb | 60 ++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 46 insertions(+), 14 deletions(-) mode change 100644 => 100755 lib/ostruct.rb diff --git a/lib/ostruct.rb b/lib/ostruct.rb old mode 100644 new mode 100755 index 82c89df..4be12e9 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -380,27 +380,59 @@ def delete_field(name, &block) end end + def self.__inspect_supports_identity_set? + true + end + InspectKey = :__inspect_key__ # :nodoc: - # - # Returns a string containing a detailed summary of the keys and values. - # - def inspect - ids = (Thread.current[InspectKey] ||= []) + # We share the same `ids` value as `Set#inspect`, so we need to use an identity Set + # only we're using a newer version of the `set` gem which is also using an identity Set. + if defined?(Set.__inspect_supports_identity_set?) && Set.__inspect_supports_identity_set? + + # + # Returns a string containing a detailed summary of the keys and values. + # + def inspect + ids = (Thread.current[InspectKey] ||= Set.new.compare_by_identity) + + detail = if ids.add?(self) + begin + @table.map { |k, v| " #{k}=#{v.inspect}" }.join(',') + ensure + ids.remove(self) + end + else + ' ...' + end - detail = if ids.include?(object_id) - ' ...' - else - ids << object_id - begin - @table.map { |k, v| " #{k}=#{v.inspect}" }.join(',') - ensure - ids.pop + ['#<', self.class!, detail, '>'].join + end + + else + + # + # Returns a string containing a detailed summary of the keys and values. + # + def inspect + ids = (Thread.current[InspectKey] ||= []) + + detail = if ids.include?(object_id) + ' ...' + else + ids << object_id + begin + @table.map { |k, v| " #{k}=#{v.inspect}" }.join(',') + ensure + ids.pop + end end + + ['#<', self.class!, detail, '>'].join end - ['#<', self.class!, detail, '>'].join end + alias :to_s :inspect attr_reader :table # :nodoc: