jackerman09 jackerman09 - 12 days ago 6
Ruby Question

Rescuing an invalid date in a rails controller

I have this in a controller:

pickuptime = params[:appointment][:pickuptime]
pickuptime = DateTime.strptime(pickuptime, "%m/%d/%Y %l:%M %p %Z")


I would like to
rescue
it if
DateTime.strptime
kicks back an
Invalid Date
error and redirect it back to the previous page with the flash message 'Invalid date'. How can I accomplish this?

I am using Ruby 2.1.2 and Rails 4.1.4. Thanks!

Answer

you can do this in your controller:

begin
  pickuptime = params[:appointment][:pickuptime]
  pickuptime = DateTime.strptime(pickuptime, "%m/%d/%Y %l:%M %p %Z")
rescue ArgumentError => e
  flash[:error] = e.message
  redirect_to :back
  return
end

The Invalid Date Error should be a ArgumentError exception with the message you want.