I wanted to be able to pretty print ActiveRecord objects, and do so in a way that’s a little bit more involved than what pp
gives you:
module ActiveRecordPrettyPrint
def pprint(ar, maxdepth=1)
pp_helper(ar, "", 0, [], maxdepth - 1)
end
private
def pp_helper(ar, buf, level, seen, maxdepth)
if level > maxdepth || seen.member?(ar)
buf << (" " * level) + "#{ar}n"
return buf
end
seen << ar
reflections = ar.class.reflections
rcolumns = reflections.collect { |k, v| v.primary_key_name }
buf << "#{ar.class}:n"
ar.attributes.keys.reject { |k| rcolumns.member? k }.each do |k|
buf << (" " * level) + "#{k} => " + ar.send(k).to_s + "n"
end
reflections.keys.each do |k|
buf << (" " * level) + k.to_s + " => "
res = ar.send(k)
if res.nil?
buf << "[nil]n"
elsif res.class == Array
res.each do |o|
pp_helper(o, buf, level + 1, seen, maxdepth)
end
else
pp_helper(res, buf, level + 1, seen, maxdepth)
buf << "n"
end
end
return buf
end
end
I suspect I’ll fix it up more as I go along, but this is the basic idea… Be careful with maxdepth
, though, or else you risk hitting the database too much.