Wednesday, 21 August 2013

Possible to refactor this if/else statement with lots of string scans?

Possible to refactor this if/else statement with lots of string scans?

I'm trying to reduce the following if/else statement...
event_description = "We have a record of item FJ750701138GB as being
delivered from Northampton North DO on 2013-08-10."
time = Time.now.strftime("%H:%M")
if date = event_description.scan(/We have a record of item [^>]* as being
delivered from [^>]* on ([^<]*)./i).join
datetime = Date.strptime("#{date} #{time}","%Y-%m-%d %H:%M").to_time
elsif date = event_description.scan(/Your item with reference [^>]* was
delivered from our [^>]* Delivery Office on ([^<]*) ./i).join
datetime = Date.strptime("#{date} #{time}","%d/%m/%y %H:%M").to_time
elsif date = event_description.scan(/Item [^>]* was collected and signed
for by the addressee on the ([^<]*) from [^>]*/i).join
datetime = Date.strptime("#{date} #{time}","%Y-%m-%d %H:%M").to_time
elsif date = event_description.scan(/Your item, posted on [^>]* with
reference [^>]* was delivered in [^>]* on ([^<]*)./i).join
datetime = Date.strptime("#{date} #{time}","%d/%m/%y %H:%M").to_time
end
event.occurred_at = datetime
The primary function of this is to scan various strings, pull the date out
of it, and create a Date object.
The dates can be in different formats (as you can see in the striptime
instances)
Over time, we'll be adding more elsif statements as we expand the strings
we're scanning, so hoping to condense this a bit so it's not so bulky.
There's a relatively decent amount of code repetition, so trying to figure
out how to refactor it a bit.

No comments:

Post a Comment