2009
11/13
16:09

Faster alternatives to ActiveRecord::Base.to_xml (Rails Performance Series)

This is part 5 of my ongoing series on Ruby on Rails performance. Today’s topic is a bit more complicated that some of the previous parts.

I’m going to explore an alternative to using the method ActiveRecord::Base.to_xml.

Before I get into that, I probably should explain why. After all, ActiveRecord::Base.to_xml is really easy to use. The alternative I’m going to demonstrate isn’t very easy to use.

The problem is that ActiveRecord::Base.to_xml can be really slow—even after making the optimizations I’ve explored in the previous parts to this series. For fairly simple AR objects, this won’t be a problem. However, when you have a deep object hierarchy and need substantial portions of it to be included in the XML response, it becomes a problem.

One instance where I encountered this was a nested has_many tree. That is, the object tree looks something like this:

ParentObject has_many ChildObjects
Each ChildObject has_many OtherObjects

The XML output is often 100k or more, and representing a few dozen or more total objects.

Read more...

2007
09/04
23:55

reading sessions in rails

in ruby’s CGI::Session module, sessions are stored as a block of seeming junk, like this: “BMZWRlcm1hbiBCb25kaW5nIENvb”. it’s actually an encoded format which is all well and fine until you need to read something out of it for debugging purposes.

if you are using rails’ ActiveRecordStore, the contents of a session can be read fairly simply. since this relies on an AR model called Session, which your app most likely doesn’t have, we’ll create that too.

so, fire up script/console and input the following:

class Session < ActiveRecord::Base ; end
CGI::Session::ActiveRecordStore::Session.unmarshal(Session.find(:first).data)

that will dump the contents of the first session. :first can be replaced with any valid option to AR’s #find method.

dump all of the sessions with something like:

Session.find(:all).collect {|s| CGI::Session::ActiveRecordStore::Session.unmarshal(s.data)}
Page: 1