lindes
lindes

Reputation: 10290

rails/ActiveRecord: How can I specify a different class for a particular attribute?

In rails 3, I have a database model that has a birthday field, of type date. For various reasons (e.g. a date without a known year), I'd like to have this be of a class other than Date, and/or to mix something in to the Date class for only objects created from this attribute. What's the best way to go about this?

For example, suppose I want to do something like:

class BirthDate < 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

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:

class Person < ActiveRecord::Base
  def bday
    BirthDate.new(birthday.year, birthday.month, birthday.day)
  end
end

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 Date doesn't seem to have a "copy constructor" type thing? (Or am I just missing it somewhere?)

Anyway, I would think that perhaps ActiveRecord might provide something that might look like:

class Person < ActiveRecord::Base
  class_for :birthday => BirthDate
end

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,

(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, some say otherwise ;))

Upvotes: 1

Views: 253

Answers (1)

rubyprince
rubyprince

Reputation: 17803

You can override the getter for the attribute manually:

def birthday
  BirthDate.parse(birthday_before_type_cast)
end

Upvotes: 1

Related Questions