Abd00s
Abd00s

Reputation: 139

Why is the .try method terminating my program?

I am capturing a string date from params that should be in the form of YYYY-DD-MM. If the parameter is an invalid date, I want nil to be assigned to minimum. Like if the param was 2013-40-50 for example. I am able to do so successfully with :

minimum = Date.try(:parse, (params[:newer_than])) if params[:newer_than].present?

If the date is of the correct format, it is assigned to minimum, otherwise nil is. However, in the case where it is nil, the program terminates and I get ArgumentError - invalid date.

The whole idea of me using .try is that if it in fact fails, it's okay, move along. I am handling the case if it were nil afterward. The error is thrown on the line assigning to minimum.

How can achieve that?

Upvotes: 0

Views: 40

Answers (2)

Ilya
Ilya

Reputation: 13487

You can use rescue for your goal:

minimum = begin
  Date.parse(params[:newer_than])
rescue ArgumentError, TypeError
  nil
end

According to docs, try just like the regular Ruby Object#send if methos defined on object, so it does not prevent errors like ArgumentError and TypeError.

Upvotes: 1

GoGoCarl
GoGoCarl

Reputation: 2519

It's the way you're using the call.

The try call is not like a begin/rescue. It just tries to call the function if it exists on that object. If the function does not exist, no biggie, it won't call the function and just proceed. Otherwise, it calls it and works as it normally would.

In this case, calling try does you no good, as you know for sure that function exists for date. What's happening is the parse function is throwing an error.

What you should do instead is go ahead and call Date.parse within a begin/rescue block, and catch those particular errors (ArgumentError) that could be thrown by the parse function. You could also pre-validate the string (using regex, for example) to ensure it's in the proper format before calling parse.

Either way, parse does not do any validation for you, so either you can check it before hand or begin/rescue the errors it throws.

Upvotes: 2

Related Questions