samhuri.net/posts/2007/05/dumping-objects-to-the-browser-in-rails.md
Sami Samhuri 007b1058b6
Migrate from Swift to Ruby (#33)
Replace the Swift site generator with a Ruby and Phlex implementation.
Loads site and projects from TOML, derive site metadata from posts.

Migrate from make to bake and add standardrb and code coverage tasks.

Update CI and docs to match the new workflow, and remove unused
assets/dependencies plus obsolete tooling.
2026-02-07 21:19:03 -08:00

1.6 KiB

Title Author Date Timestamp Tags
Dumping Objects to the Browser in Rails Sami Samhuri 15th May, 2007 2007-05-15T13:38:00-07:00 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 <pre><%= PP.pp(@something, '') %></pre> 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