Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Last active December 12, 2017 03:40
Show Gist options
  • Save rob-murray/420e39ca86b3d4eb44d6 to your computer and use it in GitHub Desktop.
Save rob-murray/420e39ca86b3d4eb44d6 to your computer and use it in GitHub Desktop.
Parse some csv data and write to a seed file for Rails
# Parse a CSV file reading certain attributes and outputting to Rails
# #create format that can be used as seed data.
#
# Not particularly good code but will do for now.
#
# Usage:
# $ ruby parse_pc_seed_data.rb
#
require 'csv'
require 'awesome_print'
file = File.open('p1.csv', 'r')
data = file.read
csv = CSV.new(data)
errors = []
plumb_center_codes = []
csv.to_a.each do |row|
values = row.first.split("\n")
puts "parsing title #{values.first}"
title_attrs = values.first.split(' - ')
unless title_attrs.size == 2
puts "unable to do anything with #{values.first}"
errors << title_attrs
next
end
name, code = *title_attrs
values.shift
details = values.join("\n").sub(/^[\n\r]*/, '') #remove the first newline char
puts "matched #{name}, #{code}"
if plumb_center_codes.include? code
puts "Already seen code #{code}"
else
# break up the output file
if plumb_center_codes.count % 10 == 0
File.open('seeds.rb', 'a') { |file| file << "\n" }
end
plumb_center_codes << code
File.open('seeds.rb', 'a') do |file|
file << "PlumbCenter.create(code: '#{code}', name: '#{name}', details: '#{details}')\n"
end
end
end
puts "matched #{plumb_center_codes.count} rows, found #{errors.size} errors."
Kernel.ap errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment