title: rails/ActiveRecord: How can I specify a different class for a particular attribute?
body: <p>In rails 3, I have a database model that has a <code>birthday</code> field, of type <code>date</code>.  For various reasons (e.g. a date without a known year), I'd like to have this be of a class other than <code>Date</code>, and/or to mix something in to the <code>Date</code> class for <em>only objects created from this attribute</em>.  What's the best way to go about this?</p>
  
  <p>For example, suppose I want to do something like:</p>
  
  <pre><code>class BirthDate &lt; Date
    def to_s
      case year
      when 1 # if I store a date with a null year, it sets it to 1
        strftime("%m/%d")
      else
        super
      end
    end
  end
  </code></pre>
  
  <p>That class does get me the behavior I want (for the moment; it's entirely possible I'll modify it in future), and I can get my model to give me access to this using something like:</p>
  
  <pre><code>class Person &lt; ActiveRecord::Base
    def bday
      BirthDate.new(birthday.year, birthday.month, birthday.day)
    end
  end
  </code></pre>
  
  <p>And then just change my views to use bday instead of birthday.  This seems kind of wasteful, though (having to create a new object from one already created -- never mind that <code>Date</code> doesn't seem to have a "copy constructor" type thing?  (Or am I just missing it somewhere?)</p>
  
  <p>Anyway, I would think that perhaps ActiveRecord might provide something that might look like:</p>
  
  <pre><code>class Person &lt; ActiveRecord::Base
    class_for :birthday =&gt; BirthDate
  end
  </code></pre>
  
  <p>Is there anything like that?  I've done a bunch of google searches, and looked through a number of docs, and haven't found it.  But since I don't know what it might be called, </p>
  
  <p>(Perhaps it's time to start digging through the source -- I've heard that's a good way to learn more about a platform.  Then again, <a href="http://scientificninja.com/blog/dont-read-source-code" rel="nofollow">some say otherwise</a> ;))</p>