Old Guy New Trick

An old guys journey to learn how to code.

Time Traveling John


Author: John on April 12, 2016

Today I would like to review some code related to a recent bug report.  We have a feature that allows the user to upload a CSV based file with their bidding information.  And altough we provided a valid formatted file for the user, when they make their updates and save the CSV file, they may make changes that can throw errors.  For example, they may add commas to the price related fields.  

The goal for this posting is to travel back in time and illustrate how I would have approached a solution when I was first starting.  Then slide forward in time to show, hopefully, an improved approach.  And then jump to current day to share the solution implemented yesterday (04/11/2016.)

# original code
def parse_file(tempfile)
  CSV.foreach(tempfile, :headers => true, :write_headers => true, :col_sep => ',') do |row|
    header_row = row.headers

    [--SNIP--]

end
# beginner me
def parse_file(tempfile)
  CSV.foreach(tempfile, :headers => true, :write_headers => true, :col_sep => ',') do |row|
    header_row = row.headers

    row['prev_rnd_price'].gsub!(',', '') if row['prev_rnd_price']
    row['clk_price'].gsub!(',', '') if row['clk_price']
    row['price'].gsub!(',', '') if row['price']
    row['back_price'].gsub!(',', '') if row['back_price']

    [--SNIP--]

end
# a better me
def parse_file(tempfile)
  CSV.foreach(tempfile, :headers => true, :write_headers => true, :col_sep => ',') do |row|
    header_row = row.headers

    currency_fields = %w(prev_rnd_price clk_price price back_price)
    currency_fields.each do |field|
      row[field].gsub!(',', '') if row[field]
    end

    [--SNIP--]

end
# optimized me
def parse_file(tempfile)
  CSV.foreach(tempfile, :headers => true, :write_headers => true, :col_sep => ',') do |row|
    header_row = row.headers

    %w(prev_rnd_price clk_price price back_price).each do |field|
      row[field].gsub!(',', '') if row[field]
    end

    [--SNIP--]

end

Was this time traveling journey helpful?  Feel free to add a comment, I do read them, or tweet at me: @hogihung

Learn Something New Everyday

 

Last Edited by: John on April 12, 2016