Rubysts, First of all, I am pretty new to Ruby, Rails and even dynamic languages in general. So please be patient with me. :-) Disclaimer given, let's get to the guts. I am trying to save a date/timestamp to my DB and comparing it with one created outside of DB/ActiveRecord afterwards. The date is burried inside an ActiveRecord object of mine and gets recorded together with everything else from it. The problem is I don't know first hand the exact type of the date object, due to duck typing. So, the date inside an object could be virtually anything because it is passed to my objects directly from client code. But in the good real world it eventually boils down to two or three types. Maybe the most significant are the Time and DateTime classes. It happens that my (mysql, if that matters) DB schema represents this particular date as a timestamp field and it is always (I think) mapped back to a Time object by ActiveRecord. The problem happens when I need to compare this ActiveRecord-converted Time object to a client-created DateTime object. The == method simply returns false, always. To get rid of the problem, the first solution I have thought of (and implemented) is to insert a to_t method in the both classes, in order to convert to a Time object. With this, every comparation I do after the conversion. That way I am effectively comparing two Time objects and the comparison is done correctly. But that solution limits the number of classes my clients can insert on the date field. I think it would be very unusual (though not impossible) for someone to insert an Integer in it, but it wouldn't be very strange to get a String. This other classes don't have the to_t method defined and I would get a nice NoMethodError when I tryed to call it. Although I almost control all client code, I wouldn't like to remember to add a to_t method to every class that I manage to insert on the date field. Besides that, I need to remember to call the to_t method everytime. The second solution I have thought of is to hide the date object creation step inside the class. I could do that by redefining the method that writes directly to the date field to receive all the date/time components and then create the date object that will get read in the future. But this way I have to change all current client code. This can be done, but I would choose to do it only if I can't find a better solution. Any thoughts? Cheers, Thiago A.
on 2006-03-10 16:53