title: Dealing with column conversions in Ruby ActiveRecord
body: <p>Dealing with a legacy database, I've come across a column in a SQL Server database where the date is stored as a decimal.  E.g. 2011-04-23 is stored as 20110423.0.</p>
  
  <p>Is there a general ActiveRecord mechanism for dealing with "weird" column storage conventions?  Enum-like columns where they're actually stored as integers is another case that might also make use of the same mechanism, but I can't quite find what I'm looking for.</p>
  
  <p>It seems like serialization gets me partly there:</p>
  
  <pre><code>class Thing &lt; ActiveRecord::Base
    class DecimalDate
      def load(date)
        if date.is_a? Numeric
          y,m,d = /^(\d\d\d\d)(\d\d)(\d\d)/.match(date.to_s)[1..3].map(&amp;:to_i)
          Date.civil(y,m,d)
        end
      end
      def dump(date)
        date ? date.strftime('%Y%m%d').to_i : 0
      end
    end
    serialize :weird_date, DecimalDate
  end
  
  rails c
  &gt; Thing.first.weird_date
  =&gt; Sun, 02 Jan 2011
  </code></pre>
  
  <p>But, the illusion is thin.  The column doesn't "know" that it's a date stored as a decimal.  E.g. comparisons fail:</p>
  
  <pre><code>rails c
  &gt; Thing.where('weird_date &gt; ?', 1.week.ago)
  ...
  ActiveRecord::StatementInvalid: ... Error converting data type varchar to numeric.:
  </code></pre>