How can I tell if an object is a "date-y" type of object in Ruby (convertable to a unix timestamp)

Viewed 2229

Specifically, if an object can be converted to a unix timestamp, I'd like to convert it to a unix timestamp. This is so I can override the standard Date / Time JSON format ruby uses to convert it to a unix timestamp for an API (since we don't want to parse strings phone side). And, I kinda wanted to do this once so I can use it in any of our objects that use dates / times (by modifying results from as_json).

Seems like I currently have to deal with Date, Time, DateTime (handled by Date if type checking), and ActiveSupport::TimeWithZone (from Rails). But, didn't want to have to check for all of those.

Any better way?

FYI, I tried checking for respond_to?(:to_datetime) which is no good since String responds to that. And respond_to?(:year) which is no good since FixedNum responds to that. :-P

2 Answers
Related