How to leave this DRY code block in Ruby

1

I have this block of code here:

if contract.amendments.empty?
  if Date.today - contract.due_date >= 30 || Date.today + contract.due_date <= 30
    @start_date = contract.due_date + 1
    @end_date = contract.due_date + 365
  elsif Date.today - contract.due_date < 30
    @start_date = Date.today
    @end_date = contract.end_date
  end
else
  last_amendment = contract.amendments.last
  if Date.today - last_amendment.due_date >= 30 || Date.today + last_amendment.due_date <= 30
    @start_date = last_amendment.end_date + 1
    @end_date = last_amendment.end_date + 365
  elsif Date.today - last_amendment.end_date < 30
    @start_date = Date.today
    @end_date = last_amendment.end_date
  end
end

And I'd like to leave you DRY, but I can not. I'm new to Ruby

    
asked by anonymous 15.04.2015 / 15:30

1 answer

1

The two codes are not exactly equivalent, the condition of elsif is very different, if they were the same (it could be an error in the code presented) would look like this:

if contract.amendments.empty?
  due_date = contract.due_date
  end_date = contract.end_date
else
  due_date = contract.amendments.last.due_date
  end_date = contract.amendments.last.end_date
end
if Date.today - due_date >= 30 || Date.today + due_date <= 30
  @start_date = due_date + 1
  @end_date = end_date + 365
elsif Date.today - end_date < 30
  @start_date = Date.today
  @end_date = end_date
end

If it was not a bug, you can still solve it:

if contract.amendments.empty?
  due_date = contract.due_date
  end_date = contract.end_date
  condition = Date.today - contract.due_date < 30
else
  due_date = contract.amendments.last.due_date
  end_date = contract.amendments.last.end_date
  condition = Date.today - last_amendment.end_date < 30
end
if Date.today - due_date >= 30 || Date.today + due_date <= 30
  @start_date = end_date + 1
  @end_date = end_date + 365
elsif condition
  @start_date = Date.today
  @end_date = end_date
end
    
15.04.2015 / 16:09