I am getting a date range from form inputs - the "from" month, day, and year, and the "to" month, day, and year, and then running a report on data for within that date range. I want to first check that the dates are valid and if not display an error indicating dates are not valid, then run the report only if valid. I want to
- make sure the dates themselves are valid, i.e., no blank inputs, and nothing like February 30th, then
- make sure the "from" date is before the "to" date.
I am having trouble doing this in a clean way with repeating myself a bunch. Here's the long way. Please help refactor with assigning to variables but only if valid.
unless Date.valid_date?(params[:from][:year].to_i,
params[:from][:month].to_i,
params[:from][:day].to_i) &&
Date.valid_date?(params[:to][:year].to_i,
params[:to][:month].to_i,
params[:to][:day].to_i)
redirect_to :back, alert: "Please provide valid date values." and return
end
unless Date.new(params[:from][:year].to_i,
params[:from][:month].to_i,
params[:from][:day].to_i) <
Date.new(params[:to][:year].to_i,
params[:to][:month].to_i,
params[:to][:day].to_i)
redirect_to :back, alert: "Please provide valid date values." and return
end
from_date = Date.new(params[:from][:year].to_i,
params[:from][:month].to_i,
params[:from][:day].to_i)
to_date = Date.new(params[:to][:year].to_i,
params[:to][:month].to_i,
params[:to][:day].to_i)
run_report(from_date, to_date)