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 !
Yury
March 20, 2010, March 20, 2010 00:31, permalink
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
Martin Plöger
March 21, 2010, March 21, 2010 21:43, permalink
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
pharmacy technician
March 31, 2010, March 31, 2010 20:26, permalink
Wow this is a great resource.. I’m enjoying it.. good article
vitaly
May 27, 2010, May 27, 2010 02:19, permalink
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"
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.