Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Converter for YAML to CSV (Excel) and back
require 'deep_merge/rails_compat'
require 'yaml'
require 'yaml2csv'
require 'time'
def convert_csv_to_yaml input_file
hash = {}
file = File.read(input_file, encoding: 'bom|utf-8')
file.split("\n").each { |line| hash.deeper_merge!(line.gsub(/"\\"|"$/, " ").gsub(/""/,'"').chomp.split(/(?<!<)\/|;/).reverse.inject() { |m,v| {v => m} }) }
return YAML.dump(hash)
end
def convert_yaml_to_csv input_file
input = File.open(input_file)
output = Yaml2csv::yaml2csv(input, :field_separator => ';')
return output
end
input_file = ARGV[0]
add_timestamp = true if ARGV[1] == "-t"
output_file = File.basename(input_file, File.extname(input_file))
if add_timestamp
timestamp = Time.now.strftime('%Y%m%d-%H%M')
output_file = timestamp+"-"+output_file unless add_timestamp == false
end
puts "Conversion started for file #{input_file}"
case File.extname(input_file)
when ".yaml"
puts "YAML-File detected, starting conversion"
output = convert_yaml_to_csv input_file
output_file = output_file+".csv"
when ".csv"
puts "CSV-File detected, starting conversion"
output = convert_csv_to_yaml input_file
output_file = output_file+".yaml"
else
puts "Error - File format not defined"
end
# Write result to output file
File.open(output_file, 'w') { |file|
file.write(output)
}
puts "DONE - You can open #{output_file}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.