SpicyCode

The ramblings of Chad Humphries

Posts Tagged ‘ehren

A serialized mystery

Ehren and I recently had to spec out a discussion filter to return only items selected by the user. While testing all things were golden. However, when we tried to step through the implementation in the browser we would have issues. After some investigation in script/console we finally found the culprit.

The breakdown of our model

The model we are filtering contains a serialized column of integers to aid with the filtering. This is a low-tech version of a full-blown association. The purpose was to insulate us from yet more expensive sub queries as the full page load can be quite intensive. (I jest not when I say we have a model named “Item” in this project.)

class Item < ActiveRecord::Base
  serialize :used_by_filter_ids
end

Calling Scotland Yard

Our investigation had us discover that the serialized column was returning an array of integers as Strings, versus actual Numerics which our callers expected. A simple tweak to the implementation to call to_i prior to handing the results back and all is good.

class Item < ActiveRecord::Base
  serialize :used_by_filter_ids

  def used_by_filter_ids
    read_attribute(:used_by_filter_ids).each(&:to_i)
  end
end

This discovery and subsequent fix explained why we were getting the errors through the browser but none during the specifications. The browser passes params around as strings, and the tests submit actual integers.

A lesson to learn

Always verify you are not relying on conversion magic at some level when serializing, or testing in general. If it needs to be an integer, use an integer. If rails will pass an integer as a string in params, you should do the same in your tests and specifications.

I estimate the time we spent in proportion to the code of size n was about O(n), but the constant hidden by the big-o notation was rather large.

Advertisements

Written by spicycode

September 15, 2007 at 6:07 pm

Posted in programming

Tagged with , ,