Sep 18

Yesterday I’ve done something I should do more often: Revisit some code written a while ago for our current project and make it better.

Let’s face it. We all write crappy code the 1st time. The difference is in what we do about it afterwards.
We might decide it’s good enough and keep moving, or we could (and should!) stop and refactor it!

The code I revisited worked as a refactoring exercise and it’s initial version is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Jphoto
 ...
 
 #a few other methods ...
 
 def post_photo(file_data, hotel_id, send_rss, options = {})
   file_name = "tmp/#{Time.now.to_i}_#{rand(1000000).to_s(36)}"
   File.open(file_name, "wb") do |f|
     f.puts(file_data)
   end
 
   params = [Curl::PostField.file('photo',file_name),
      Curl::PostField.content('hotel', hotel_id),
      Curl::PostField.content('source','PhotoUploadTest')]
   extract_extra_params!(params, options)
 
   c = Curl::Easy.new("#{service_uri_base']}/photoupld")
   c.multipart_form_post = true
   c.http_post(*params)
 
   if c.response_code != 200
     error_msg = "File upload failed with code: #{c.response_code}"
     Rails.logger.info error_msg
     raise error_msg
   end
 
   File.delete(file_name)
 
   hotel = Hotel.find_by_id(hotel_id)
   hotel.cache.destroy_all
 
   send_upload_rss(hotel, original_upload_url(c.body_str) , options) if send_rss
 end
 
 private
 
 def send_upload_rss(hotel, photo_url, options)
   ...
 end
 def manage_images_link(hotel_id)
   ...
 end
 
 def extract_extra_params!(params, options)
   params << Curl::PostField.content('status', options[:status]) if options[:status]
   params << Curl::PostField.content('upload_source', options[:upload_source]) if options[:upload_source]
   params << Curl::PostField.content('uploader_ip', options[:uploader_ip]) if options[:uploader_ip]
   params << Curl::PostField.content('uploader_email', options[:uploader_email]) if options[:uploader_email]
 end
end

Continue reading »

Tagged with:
preload preload preload