samhuri.net


By Sami J. Samhuri

Dumping Objects to the Browser in Rails

Here's an easy way to solve a problem that may have nagged you as it did me. Simply using foo.inspect to dump out some object to the browser dumps one long string which is barely useful except for short strings and the like. The ideal output is already available using the PrettyPrint module so we just need to use it.

Unfortunately typing

<%= PP.pp(@something, '') %>
to quickly debug some possibly large object (or collection) can get old fast so we need a shortcut.

Taking the definition of Object#pp_s from the extensions project it's trivial to create a helper method to just dump out an object in a reasonable manner.

/app/helpers/application_helper.rb
def dump(thing)
  s = StringIO.new
  PP.pp(thing, s)
  s.string
end

Alternatively you could do as the extensions folks do and actually define Object#pp_s so you can use it in your logs or anywhere else you may want to inspect an object. If you do this you probably want to change the dump helper method accordingly in case you decide to change pp_s in the future.

lib/local_support/core_ext/object.rb
class Object
  def pp_s
    pps = StringIO.new
    PP.pp(self, pps)
    pps.string
  end
end