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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With