to_readable instead of to_yaml
class Object
# Similar to to_yaml method but makes text much more readable to human.
# Use this method instead of to_yaml if you need to dump object
# into communications with humans (like in internal automatic emails to tech team/support team)
def to_readable
if self.respond_to?(:attributes)
ignore = ['encrypted_password'] # dont show these attributes
h = self.attributes.except(*ignore).to_h
hash_to_readable(h)
elsif self.is_a?(ActionController::Parameters)
hash_to_readable(self.to_unsafe_h)
elsif self.is_a?(NilClass)
'nil'
elsif self.is_a?(TrueClass) || self.is_a?(FalseClass) || self.is_a?(String) || self.is_a?(Fixnum) ||
self.is_a?(Float) || self.is_a?(BigDecimal) || self.is_a?(Bignum) || self.is_a?(Time) ||
self.is_a?(DateTime)
self.to_s
elsif self.is_a?(Exception)
self.message
elsif self.respond_to?(:to_yaml)
self.to_yaml(line_width: -1)
else
self.to_s
end
rescue => ex
self.to_yaml
end
#
# PRIVATE
#
private
def hash_to_readable(h)
return '' if h.blank?
max_key_len = h.keys.max_by {|k| k.to_s.length }.to_s.length
h.reduce("\n") do |sum, (k, v)|
sum += "\t#{(k.to_s + ':').ljust(max_key_len + 1)} #{v.to_readable}\n"
end
end
end
Written by oleh_the_great
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Related Tags
#rails
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#