Search code examples
rubyrescueto-date

Ruby string date to_date with try yields invalid date


I want to try get a date from params into a date format, and if it can't then i would like to then assign it to a date from a year today.

This is what i tried.

valid_until = params[:valid_until].try(:to_date) || Date.today.next_year

The try method is cool because if the :valid_until date is nil it will just return nil. What i found though, is that if someone has an invalid date like "4790224374" then it will return a ArgumentError as invalid date. the :valid_until date will still be run against to_date.

I guess having this with a rescue seems like the only answer, just wondering if there is a smarter way of trying to cater for nils and invalid date errors, before setting it to the default next year.

EDIT:

You can read up about Try here.

You can read up about to_date here


Solution

  • You are misusing Object.try. This method is meant to fail silently if a method does not exist on an object. In this case, the method is there (so it is called) and that method fails.

    This is not meant to replace a try/rescue block. A possible implementation is below.

    def expiration_date(a_string)
      Date.parse(a_string)
    rescue
      Date.today.next_year
    end
    
    valid_until = expiration_date(params[:valid_until])