Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 533
stuckj Avatar asked Dec 06 '13 16:12

stuckj


1 Answers

Instead of using respond_to?

why don't you do:

def date_or_time?(obj)
  obj.kind_of?(Date) || obj.kind_of?(Time)
end

[19] pry(main)> a = Date.new
=> #<Date: -4712-01-01 ((0j,0s,0n),+0s,2299161j)>
[20] pry(main)> date_or_time? a
=> true
[21] pry(main)> b = DateTime.new
=> #<DateTime: -4712-01-01T00:00:00+00:00 ((0j,0s,0n),+0s,2299161j)>
[22] pry(main)> date_or_time? b
=> true
[23] pry(main)> c = Time.new
=> 2013-12-06 10:44:57 -0600
[24] pry(main)> date_or_time? c
=> true
like image 177
bjhaid Avatar answered Sep 28 '22 09:09

bjhaid