693a4661eaa71435ce5ebe61de64c5a4

I have the following code where I parse a text and try to retrieve some information to store it in a database. Unfortunately sometimes there is no data and I have to set the value to "null". Essentially I have just a couple of these blocks there. My approach just does not seem right.

begin
  data["body"] = content[1].split(/\W{2,}/)[0].strip()
rescue Exception => e
  data["body"] = "null"
end
begin
  data["height"] = content[2].split(/\W{2,}/)[0].strip()
rescue Exception => e
  data["height"] = "null"
end
begin
  data["status"] = content[7].split(/\W{2,}/)[0].strip()
rescue Exception => e
  data["status"] = "null"
end
begin
  data["country"] = content[8].split(/\W{2,}/)[1].strip()
rescue Exception => e
  data["country"] = "null"
end
begin
  data["zip"] = content[9].split(/\W{2,}/)[0].strip()
rescue Exception => e
  data["zip"] = "null"
end
begin
  data["location"] = content[10].split(/\W{2,}/)[0].strip()
rescue Exception => e
  data["location"] = "null"
end

Refactorings

No refactoring yet !

1ad8d2ae1c644eb22e8d1bbf5f81300f

Yury

March 20, 2010, March 20, 2010 00:31, permalink

2 ratings. Login to rate!

Something like this. But still need to cleanup your regexp...

mappings = {
  "body"     => { :content_index => 1 },
  "height"   => { :content_index => 2 },
  "status"   => { :content_index => 7 },
  "country"  => { :content_index => 8, :regexp_index => 1},
  "zip"      => { :content_index => 9},
  "location" => { :content_index => 10}
}
  
mappings.each |key, opts| do
  data[key] = content[opts[:content_index]].split(/\W{2,}/)[opts[:regexp_index] || 0].strip() rescue "null"
end
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

March 21, 2010, March 21, 2010 21:43, permalink

2 ratings. Login to rate!

I just recycled Yury's great refactoring and used Array instead of hashes. Hope it is not less readable.

mappings = ['body', 1], ['height', 2], ['status', 7], ['country', 8, 1], ['zip', 9], ['location', 7]
mappings.each do |key, content_index, regexp_index| 
  data[key] = content[content_index].split(/\W{2,}/)[regexp_index || 0].strip rescue 'null'
end
1b6e26633e1ebea63c21f126c3da08e0

pharmacy technician

March 31, 2010, March 31, 2010 20:26, permalink

No rating. Login to rate!

Wow this is a great resource.. I’m enjoying it.. good article

996b64c2708771eb4f0c479e0d3a0646

vitaly

May 27, 2010, May 27, 2010 02:19, permalink

No rating. Login to rate!
data["body"] = content[1].split(/\W{2,}/)[0].strip() rescue "null"
  data["height"] = content[2].split(/\W{2,}/)[0].strip() rescue "null"
  data["status"] = content[7].split(/\W{2,}/)[0].strip() rescue "null"
  data["country"] = content[8].split(/\W{2,}/)[1].strip() rescue "null"
  data["zip"] = content[9].split(/\W{2,}/)[0].strip() rescue "null"
  data["location"] = content[10].split(/\W{2,}/)[0].strip() rescue "null"

Your refactoring





Format Copy from initial code

or Cancel