Skip to content

Instantly share code, notes, and snippets.

@deepak
Created November 14, 2013 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepak/7466461 to your computer and use it in GitHub Desktop.
Save deepak/7466461 to your computer and use it in GitHub Desktop.
parsing and validating dates in ruby. Have an icky feeling
def parse_date(date)
if date.is_a?(Integer)
parse_date_from_timestamp(date)
elsif date.is_a?(String)
if date.to_i.to_s == date
parse_date_from_timestamp(date.to_i)
else
parse_date_from_string(date)
end
elsif date.acts_like?(:date) || date.acts_like?(:time)
# acts_like(:date || :time) defined in activesupport/core_ext
date
else
raise ArgumentError, "date can be an timestamp or a string"
end
end
def parse_date_from_timestamp(timestamp)
Time.at(timestamp)
end
def parse_date_from_string(date)
# can raise TypeError
# if for eq. we pass in a symbol - needs string
# or can raise `ArgumentError: invalid date`
# in case date is invalid
Date.parse(date)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment