Skip to content

Instantly share code, notes, and snippets.

@arvindravi
Created May 9, 2016 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arvindravi/acee24a5d6aee16f3584f3792b90d8e8 to your computer and use it in GitHub Desktop.
Save arvindravi/acee24a5d6aee16f3584f3792b90d8e8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'csv'
require 'optparse'
require 'ostruct'
# Opt Parser
options = OpenStruct.new
OptionParser.new do |opts|
opts.banner = "Usage: ./test.rb [options]"
opts.on('-c', '--csv [CSV File]', 'Path of the CSV to be parsed') do |n|
options.csv = n || nil
end
opts.on('-a', '--array_one [ARRAY]', 'First Array') do |array|
array_one = array.split(",").to_a
options.array_one = array_one || nil
end
opts.on('-b', '--array_two [ARRAY]', 'Second Array') do |array|
array_two = array.split(",").to_a
options.array_two = array_two || nil
end
opts.on('-e', '--export [FILENAME]', 'Export CSV to File') do |filename|
options.export = true
options.export_filename = filename
end
opts.on('-v', '--verbose', 'Verbose Mode') do
options.verbose = true
end
end.parse!
# Inputs
array_one = options.array_one || ["teen_star"]
array_two = options.array_two || ["tv_stars", "old_stars"]
csv = options.csv || 'test.csv'
# CSV Parse
table = CSV.table(csv, headers: true)
# Enumerator to make the script performant
rows = table.each
# Case I
rows.each do |master_row|
if array_one.include? master_row[:source]
rows.delete_if { |row| row[:email] == master_row[:email] }
end
end
# Case II
emails = []
index = {}
prev_email = nil
rows.each do |master_row|
prev_email = master_row[:email]
email_index = emails.index master_row[:email]
index[master_row[:source]] = array_two.index(master_row[:source]) if array_two.include? master_row[:source]
if email_index.nil?
emails << master_row[:email]
else
rows.delete_if do |row|
index[row[:source]] != index.values.min if prev_email == row[:email] and emails.include? row[:email]
end
end
end
# Packaging Options
if options.verbose
rows.each { |r| puts r.inspect }
end
if options.export
puts "Exporting.."
CSV.open(options.export_filename, "wb") do |csv|
rows.each do |row|
csv << row
end
end
puts "File #{options.export_filename} has been created."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment