module String::SafeInspector
Get `#inspect` without `exception` and `nil` possibilities
Constants
- BUILTIN_INSPECT_METHOD
Might be unusable when bugs.ruby-lang.org/issues/12164 selects changing spec direction
- FINAL_FALLBACK
Used when there is nothing that can be done
- VERSION
Public Class Methods
inspect_for(object)
click to toggle source
@return [String]
# File lib/string/safe_inspector.rb, line 18 def self.inspect_for(object) first_choice = begin String.try_convert(object.inspect) rescue Exception nil end (first_choice || second_choice_for(object) || fallback_for(object)).dup end
Private Class Methods
fallback_for(object)
click to toggle source
@return [String]
# File lib/string/safe_inspector.rb, line 36 def self.fallback_for(object) # This implementation used `RSpec::Support::ObjectFormatter::UninspectableObjectInspector` as a reference, thank you! # ref: https://github.com/kachick/times_kachick/issues/97 # Pry looks to do similar way too :) https://github.com/pry/pry/blob/0aae8c94ad03a732659ed56dcd5088469a15eebf/lib/pry/color_printer.rb#L55-L64 singleton_class = class << object; self; end begin klass = singleton_class.ancestors.detect { |ancestor| !ancestor.equal?(singleton_class) } "#<#{klass}:#{'%#016x' % (object.__id__ << 1)}>" rescue Exception FINAL_FALLBACK end end
second_choice_for(object)
click to toggle source
@return [String, nil]
# File lib/string/safe_inspector.rb, line 29 def self.second_choice_for(object) String.try_convert(BUILTIN_INSPECT_METHOD.bind(object).call) rescue Exception nil end